内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”,方法比较少,这些信息储存在类的私有变量中,通过set()、get()获得。
PropertyDescriptor
先看实例:
package me.yanand.pojo; /** * 普通java bean */ public class Student { private long id; private String name; private int age; public Student() { } public Student(long id, String name, int age) { this.id = id; this.name = name; this.age = age; } public long getId() { return id; } public void setId(long id) { this.id = id; } 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; } }
PropertyDescriptor操作:
package me.yanand; import me.yanand.pojo.Student; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Test { public static void main(String[] args) throws IllegalAccessException, IntrospectionException, InvocationTargetException { Student student = new Student(); setProperty(student,"name","张三"); getProperty(student,"name"); } public static void setProperty(Student student,String keyName,String value) throws IntrospectionException, InvocationTargetException, IllegalAccessException { //获取Student描述类 PropertyDescriptor propertyDescriptor = new PropertyDescriptor(keyName,Student.class); //获取用于写入值的方法 Method method = propertyDescriptor.getWriteMethod(); //写入值 method.invoke(student,value); System.out.println(student.getName()); } public static void getProperty(Student student,String keyName) throws IntrospectionException, InvocationTargetException, IllegalAccessException { //获取Student描述类 PropertyDescriptor propertyDescriptor = new PropertyDescriptor(keyName,Student.class); //获取用于读值的方法 Method method = propertyDescriptor.getReadMethod(); //读值 Object oj = method.invoke(student); System.out.println(oj.toString()); } }
在类Student中有属性name,那我们可以通过getName, setName来得到其值或者设置新的值。通过getName/setName来访问name属性,这就是默认的规则。Java JDK中提供了一套API用来访问某个属性的getter/setter方法,这就是内省。
Introspector
将JavaBean中的属性封装起来进行操作。在程序把一个类当做JavaBean来看,就是调用Introspector.getBeanInfo()方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息,即属性的信息。
public static void setProperty2(Student student,String keyName, String value) throws IntrospectionException, InvocationTargetException, IllegalAccessException { BeanInfo beanInfo = Introspector.getBeanInfo(Student.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor p:propertyDescriptors){ if(p.getName().equals(keyName)){ p.getWriteMethod().invoke(student,value); break; } } }
转载请注明:Terry's blog » java内省机制-Introspector、PropertyDescriptor类使用