内省(Introspector)

1.为什么要学内省?
开发框架时,经常需要使用Java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性。

2.什么是java对象的属性和属性的读写方法?

内省访问JavaBean属性的两种方式:
1)通过PropertyDescriptor类操作Bean的属性
2)通过Introspector类获得Bean对象的BeanInfo,然后通过BeanInfo来获取属性的描述器(PropertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后通过反射机制来调用这些方法。

3.

代码1(Person 类):

package cn.itcast.introspector;

public class Person { //javabean封装用户数据
private String name;//字段
private String password;//字段
private int age;//字段
public String getAb() {//属性
return null;
}
public String getName() {//属性
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}

 

代码2(Demo1 类):

package cn.itcast.introspector;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import org.junit.Test;

//使用内省api操作bean的属性
public class Demo1 {
// 得到bean的所有属性
@Test
public void test1() throws Exception {
BeanInfo info = Introspector.getBeanInfo(Person.class, Object.class);
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
}
}

// 操纵bean的指定属性:age
@Test
public void test2() throws Exception {
Person p = new Person();
PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);

// 得到属性的写方法,为属性赋值
Method method = pd.getWriteMethod();
method.invoke(p, 45);

// 获取属性的值
method = pd.getReadMethod();
System.out.println(method.invoke(p, null));
}

// 高级点的内容:获取当前操作的属性的类型
@Test
public void test3() throws Exception {
Person p = new Person();
PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
System.out.println(pd.getPropertyType());
}
}

 

posted @ 2015-03-23 10:43  LittlePenguin  阅读(202)  评论(0编辑  收藏  举报