内省(Introspector)是Java 语言对Bean类属性、事件的一种缺省处理方法。
1、新建一个javabean
package com.study.introspector;
public class Emp {
private String name;
private int age;
public Emp(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
2、内省操作
package com.study.introspector;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class TestIntrospector {
public static void main(String[] args) throws Exception{
//实例化Emp
Emp emp = new Emp("yy",24);
//通过Introspector获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(emp.getClass());
//通过BeanInfo获取所有的属性描述
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//遍历
for(PropertyDescriptor pd : pds){
//如果获取的属性为name
if(pd.getName().equals("name")){
//则获取name属性对应的读方法,即:getName方法
Method methodGetName = pd.getReadMethod();
//通过反射调用获取name值
Object nameRetVal = methodGetName.invoke(emp);
//打印结果为 yy
System.out.println(nameRetVal);
//接着通过内省的方式为name赋新值:yy_new
Method methodSetName = pd.getWriteMethod();
methodSetName.invoke(emp, "yy_new");
//打印结果为yy_new
Object nameRetVal2 = methodGetName.invoke(emp);
System.out.println(nameRetVal2);
}
}
//第二种方式
//通过构造器构造PropertyDescriptor对象
PropertyDescriptor pd2 = new PropertyDescriptor("age", emp.getClass());
//获取读方法
Method methodGetAge = pd2.getReadMethod();
//反射调用
Object ageRetVal = methodGetAge.invoke(emp);
//打印结果 24
System.out.println(ageRetVal);
//获取写方法
Method methodSetAge = pd2.getWriteMethod();
//设新值
methodSetAge.invoke(emp, 25);
//反射调用读
Object ageRetVal2 = methodGetAge.invoke(emp);
////打印结果 25
System.out.println(ageRetVal2);
}
}
3、结果
yy
yy_new
24
25