import java.lang.reflect.Field; import java.lang.reflect.Method; import com.thoughtworks.paranamer.*; public class ReflectionExample { public static void main(String[] args) throws Exception { Class<?> clazz = ExampleClass.class; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { System.out.println("Field name: " + field.getName()); } Method[] methods = clazz.getDeclaredMethods(); ParameterNameDiscoverer paramDiscoverer = new CachingParanamer(); for (Method method : methods) { System.out.println("Method name: " + method.getName()); String[] paramNames = paramDiscoverer.getParameterNames(method); for (String paramName : paramNames) { System.out.println("Parameter name: " + paramName); } } } } class ExampleClass { private String exampleField; public void exampleMethod(String param1, int param2) { } } import java.beans.PropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.io.*; public class SerializationExample { public static void main(String[] args) throws IOException, ClassNotFoundException, IntrospectionException { ExampleClass object = new ExampleClass(); object.setExampleField("example"); FileOutputStream fos = new FileOutputStream("example.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object); oos.close(); FileInputStream fis = new FileInputStream("example.ser"); ObjectInputStream ois = new ObjectInputStream(fis); ExampleClass deserializedObject = (ExampleClass) ois.readObject(); ois.close(); PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(ExampleClass.class).getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Object value = propertyDescriptor.getReadMethod().invoke(deserializedObject); System.out.println(propertyDescriptor.getName() + " = " + value); } } } class ExampleClass implements Serializable { private String exampleField; public void setExampleField(String exampleField) { this.exampleField = exampleField; } public String getExampleField() { return exampleField; } } <dependency> <groupId>com.thoughtworks.paranamer</groupId> <artifactId>paranamer</artifactId> <version>2.8</version> </dependency>


上一篇:
下一篇:
切换中文