Java内省一般是对Java中JavaBean的属性,事件,方法等的一些缺省处理方法,也是一些规则,其中主要用到反射。有关类主要在rt.jar包的java.beans下面,一看到这个包就很清楚都是关于bean,大家看的时候最好打开源码一块看
对于JavaBean来说其实就是一些遵守了特定规则的Java类而已,比如
- 这个类需要是public 的, 然后需要有个无参数的构造函数
- 这个类的属性应该是private 的, 通过setXXX()和getXXX()来访问
- 这个类需要能支持“事件”, 例如addXXXXListener(XXXEvent e), 事件可以是Click事件,Keyboard事件等等, 当然咱们也支持自定义的事件。
- 我们得提供一个所谓的自省/反射机制, 这样能在运行时查看java bean 的各种信息“
- 这个类应该是可以序列化的, 即可以把bean的状态保存的硬盘上, 以便以后来恢复。
Introspector 这个类里面提供了一个静态方法getBeanInfo
返回一个BeanInfo,这是一个接口,它提供了关于Bean的属性,事件,方法的描述 。在描述类里面分别可以获取到有关Bean的一些信息
举个例子
public class PersonBean implements Serializable {
private int age;
private String name;
public PersonBean() {
}
public PersonBean(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class IntroSpectTest {
public static void main(String[] args) throws Exception {
PersonBean personBean = new PersonBean(10, "zhangsan");
//通过反射获取PersonBean的info类
BeanInfo beanInfo = Introspector.getBeanInfo(PersonBean.class,Introspector.IGNORE_ALL_BEANINFO );
//获取PersonBean的属性信息
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
//获取属性的类型
Class<?> propertyType = propertyDescriptor.getPropertyType();
System.out.println("propertyType:" + propertyType.getName());
//获取属性名称
String propertyName = propertyDescriptor.getName();
System.out.println("propertyName:" + propertyName);
//获取与属性相对应的get方法
Method readMethod = propertyDescriptor.getReadMethod();
//获取与属性对应的set方法
Method writeMethod = propertyDescriptor.getWriteMethod();
// age
if (propertyName.equals("age")) {
//执行get方法
System.out.println("执行set方法前 get:"+readMethod.invoke(personBean));
//执行set方法
writeMethod.invoke(personBean,15);
System.out.println("执行set方法后:"+propertyName+"="+readMethod.invoke(personBean));
} else if (propertyName.equals("name")) {//name 属性
//执行get方法
System.out.println("执行set方法前 get:"+readMethod.invoke(personBean));
//执行set方法
writeMethod.invoke(personBean,"lisi");
System.out.println("执行set方法后:"+propertyName+":"+readMethod.invoke(personBean));
}
System.out.println("-------------");
}
}
}
打印结果
内省主要在看各种框架的时候可能会用的到,在自己写业务代码的时候用的不多, apache commons子项目中提供了一个commons-beanutils的一个软件包,其主要目的是利用反射机制对JavaBean的属性进行处理。想要了解的同学看看它的API就可以了