1. 反射和自省(Reflection 和 Introspection )
自省
@Test
public void test01() throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(A.class);
System.out.println("beanInfo: "+beanInfo);
A test0 = new A(0, "test0");
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
System.out.println("=========================");
System.out.println(propertyDescriptor.getName());
Method readMethod = propertyDescriptor.getReadMethod();
Method writeMethod = propertyDescriptor.getWriteMethod();
Object invoke = readMethod.invoke(test0);
System.out.println(invoke);
System.out.println("调用set方法后");
String name = propertyDescriptor.getName();
System.out.println("propertyDescriptor.getName(): " + name);
if (name.equals("age")) {
Object test = writeMethod.invoke(test0, 1);
}else if (name.equals("class")) {
continue;
}else {
Object test = writeMethod.invoke(test0, "test1");
}
Object invoke1 = readMethod.invoke(test0);
System.out.println(invoke1);
Method readMethod1 = propertyDescriptor.getReadMethod();
Object invoke2 = readMethod1.invoke(test0);
System.out.println(invoke2);
System.out.println("=========================");
}
String abc = Introspector.decapitalize("abc");
System.out.println("字符串转换为java变量名称大写: "+abc);
}
2. 获取Class类的方法
Test test = new Test();
Class c1 = test.getClass();
Class c2=Test.class;
Class c3=Class.forName("ClassTest.Test");
3.反射的使用
Field[] fields = oldBean.getClass().getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd1 = new PropertyDescriptor(field.getName(), clazz1);
Method getMethod1 = pd1.getReadMethod();
Object o1 = getMethod1.invoke(oldBean);
}