简单理解:
内省相当于是反射的一个子集。
内省专门用来操作Bean的。
关于bean:一个set/get就定义了一个属性(包括从父类继承来的get/set)
简易代码示例:
一个bean:Person.java,一个内省Demo:Demo_istpt.java
Person.java:
1 package com.rt.gwq.introspector; 2 3 public class Person { 4 5 private String name ; 6 private String password ; 7 private int age ; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public String getPassword() { 15 return password; 16 } 17 public void setPassword(String password) { 18 this.password = password; 19 } 20 public int getAge() { 21 return age; 22 } 23 public void setAge(int age) { 24 this.age = age; 25 } 26 27 }
Demo_istpt.java:
1 package com.rt.gwq.introspector; 2 3 import java.beans.BeanInfo; 4 import java.beans.IntrospectionException; 5 import java.beans.Introspector; 6 import java.beans.PropertyDescriptor; 7 import java.lang.reflect.Method; 8 9 import org.junit.Test; 10 11 public class Demo_istpt { 12 13 /** 14 * 获取所有属性描述器 15 * @throws Exception 16 */ 17 @Test 18 public void test1() throws Exception{ 19 20 //获取一个Bean的信息 21 BeanInfo info = Introspector.getBeanInfo(Person.class); 22 //下面语句只获得Person的属性,不包括从Object继承的属性 23 // BeanInfo info = Introspector.getBeanInfo(Person.class,Object.class); 24 //获取bean属性的所有描述器 25 PropertyDescriptor[] pds = info.getPropertyDescriptors(); 26 for (PropertyDescriptor pd : pds) { 27 System.out.println(pd.getName()); 28 } 29 30 } 31 32 /** 33 * 通过内省操作Bean方法 34 * @throws Exception 35 */ 36 @Test 37 public void test2() throws Exception{ 38 39 Person p = new Person(); 40 41 PropertyDescriptor pd = new PropertyDescriptor("age", Person.class); 42 //获取写方法,即set方法 43 Method w = pd.getWriteMethod(); 44 w.invoke(p, (Integer)18); 45 //获取读方法,get方法 46 Method r = pd.getReadMethod(); 47 //输出验证 48 System.out.println("age:"+ r.invoke(p, null)); 49 //获取类型 50 System.out.println("age type:"+pd.getPropertyType()); 51 52 53 } 54 55 }