一、什麼是內省?spring
內省(Introspector)是Java語言對Javabean類屬性、方法的一種缺省處理方法。數組
JavaBean是一種特殊的類,主要用於傳遞數據信息,這種類中的方法主要用於訪問私有的字段,且方法名符合某種命名規則。若是在兩個模塊之間傳遞信息,能夠將信息封裝進JavaBean中,這種對象稱爲「值對象」(Value Object),或「VO」。將這些信息儲存在類的私有變量中,經過set()、get()得到。如:this
public class Person {
private String name;
private int 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;
}
}spa
在Person類中有屬性name,那咱們能夠經過getName(),setName()來獲得其值或設置新的值。經過getName(),setName()來訪問name屬性,這就是默認的規則。Java JDK中提供了一套API用來訪問某個屬性的getter/setter方法,這就是內省。對象
JDK內省類庫:ip
PropertyDescriptor類:該類表示JavaBean類經過存儲器導出一個屬性。主要方法:(1)getName()獲取屬性名,(2)getPropertyType()獲取屬性的Class對象,(3)getReadMethod()得到用於讀取屬性值的方法;getWriteMethod()得到用於寫入屬性值的方法。get
Introspector類: 將JavaBean中的屬性封裝起來進行操做。在程序中把一個類當作JavaBean來看,就是調用Introspector.getBeanInfo(class)方法,獲得的BeanInfo對象封裝了把這個類當作JavaBean來看的結果信息,即屬性的信息。getPropertyDescriptors(),得到屬性的描述,放在PropertyDescriptor[]數組中,來查找、設置類的屬性。it
二、內省怎麼用?io
1)操做一個屬性class
如只操做Person類中的age屬性:
PropertyDescriptor pro = new PropertyDescriptor("age", Person.class);
Person person = new Person();
Method method = pro.getWriteMethod();
method.invoke(person, 12);
System.out.println(pro.getReadMethod().invoke(person));
2)操做多個屬性
PropertyDescriptor[] pro = Introspector.getBeanInfo(Person.class).getPropertyDescriptors();
Person p = new Person();
System.out.print("Person的屬性有:");
for (PropertyDescriptor pr : pro) {
System.out.print(pr.getName() + " ");
}
System.out.println("");
for (PropertyDescriptor pr : pro) {
// 獲取bean的set方法
Method writeme = pr.getWriteMethod();
if (pr.getName().equals("name")) {
// 執行方法
writeme.invoke(p, "xiong");
}
if (pr.getName().equals("age")) {
writeme.invoke(p, 23);
}
// 獲取bean的get方法
Method method = pr.getReadMethod();
System.out.print(method.invoke(p) + " ");
}
或
Class<?> cl = Class.forName("com.ushareit.springMaven.Person");
BeanInfo beaninfo = Introspector.getBeanInfo(cl, Object.class);
PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors();
Person p = new Person();
System.out.print("Person的屬性有:");
for (PropertyDescriptor pr : pro) {
System.out.print(pr.getName() + " ");
}
System.out.println(""); for (PropertyDescriptor pr : pro) { // 獲取bean的set方法 Method writeme = pr.getWriteMethod(); if (pr.getName().equals("name")) { // 執行方法 writeme.invoke(p, "xiong"); } if (pr.getName().equals("age")) { writeme.invoke(p, 23); } // 獲取bean的get方法 Method method = pr.getReadMethod(); System.out.print(method.invoke(p) + " "); }