中国文化之博大精深之内省还是内省,究竟他是读(xing)还是(sheng)呢,通过百度引擎貌似晓得,他是读(xing)。
下面我们就对内省做一下简单介绍:
1.内省是java语言对bean类属性、事件的一种处理方法
2.为什么要学内省?开发框架时,经常需要使用java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性。
3.内省访问JavaBean属性的两种方式:
通过PropertyDescriptor类操作Bean的属性
通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。
下面写一下测试代码
Java代码
/*
* 通过Introspector类获得Bean对象的 BeanInfo, 然后通过 BeanInfo 来获取属性的描述器(
* PropertyDescriptor ) 通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,
* 然后通过反射机制来调用这些方法。
*/
@Test
public void test() throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Student st = new Student();
// 1、通过Introspector类获得Bean对象的 BeanInfo,
BeanInfo entity = Introspector.getBeanInfo(Student.class);
// 2、然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor )
PropertyDescriptor pdrs[] = entity.getPropertyDescriptors();
// 3、通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,
for (PropertyDescriptor pd : pdrs) {
// System.out.println(pd.getName());
/*
* System.out.println(pd.getShortDescription());
* System.out.println(pd.getDisplayName());
*/
if (pd.getName().equals("age")) { //age是什么类型?
Method md = pd.getWriteMethod();
md.invoke(st, 12);
}
}
// System.out.println(st.getAge());
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
bean类
Java代码
package cn.csdn.Introspector;
public class Student {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String email;
public String getXxx(){
return "Longmanfei";
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
【编辑推荐】