内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得
Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法,这就是内省。
package com.liang.Instopector;
import java.io.Serializable;
import java.util.Date;
public class Student implements Serializable {
private String name="liang";
private int age=21;
private Date birthday;
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;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
package com.liang.Instopector;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;
import org.junit.Test;
public class Demo {
@Test
public void test1() throws Exception{
//获得指定的beanInfo对象
BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
//获得属性描述数组
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//遍历:因为类继承Object类,Object类中有一个getClass()方法,所以个数会比你写的多一个
System.out.println(pds.length);
for(PropertyDescriptor pd:pds){
System.out.print(pd.getName()+" ");
}
System.out.println();
//获得指定的PropertyDescriptor
PropertyDescriptor pd=new PropertyDescriptor("name", Student.class);
//获得get方法
Method m=pd.getReadMethod();
Student s=new Student();
String str=(String)m.invoke(s, null);
System.out.println(str);
//获得set方法
Method m1=pd.getWriteMethod();
m1.invoke(s, "aaa");
System.out.println(s.getName());
}
}