java中的内省
1:内省是什么:
1:内省是利用getter setter方法 再利用反射获取属性属性,并对属性进行操作的
一种方法,因为getter setter 方法是getSHU性名() setSHU性名的形式存在,
jdk可以通过这个形式不难找出属性名,并利用反射得到属性
2:在框架中为了获取Javabean属性,并且对属性进行操作,如果属性过多,我们是不是
需要编写大量的重复的代码去getDeclearedFeild() 属性呢?当然不会,内省就有
一大懒招获取所有属性。
3:内省通过PropertyDescriptor和Introspector实现
4:过程
Introspector获取某对象的BeanInfo 然后通过BeanInfo 获取属性描述器;通过描述器获取某属性的
getter setter 然后到反射获取方法
5:实例
public class Person {
private String name;
private int age;
//getter setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//获取所有getter setter发方法
public void testGetProperty() throws IllegalAccessException, InstantiationException, IntrospectionException {
//获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
//获取Descriptor
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
System.out.println(pds.length);
//遍历
for (PropertyDescriptor pd : pds) {
//获取getter方法
Method readMethod = pd.getReadMethod();
System.out.println(readMethod.getName());
//获取setter 方法
Method writeMethod = pd.getWriteMethod();
if (writeMethod!=null){
System.out.println(writeMethod.getName());
}
}
/**
* 3
* getAge
* setAge
* getClass
* getName
* setName
*/
}
//读取属性值
@Test
public void getProperty() throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
//类对象
Class<Person> p = Person.class;
//实例
Person instance = p.newInstance();
instance.setName("珍君");
PropertyDescriptor name = new PropertyDescriptor("name", p);
//过去getter
Method readMethod = name.getReadMethod();
System.out.println("执行");
Object value = readMethod.invoke(instance);
System.out.println(value);
Assert.assertEquals("珍君", value);
System.out.println("结束");
/**
* 执行
* 珍君
* 结束
*/
}
//写入并读取属性
@Test
public void setProperty() throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
//类对象
Class<Person> pc = Person.class;
//实例
Person instance = pc.newInstance();
//Descriptor
PropertyDescriptor name = new PropertyDescriptor("name", pc);
//setter
Method writeMethod = name.getWriteMethod();
System.out.println("开始");
writeMethod.invoke(instance, "珍君");
Assert.assertEquals("珍君", instance.getName());
Method readMethod = name.getReadMethod();
Object value = readMethod.invoke(instance);
System.out.println(value);
System.out.println("结束");
/**
*开始
* 珍君
* 结束
*/
}