java(11)--内省

来源:互联网 发布:淘宝代理靠谱吗 编辑:程序博客网 时间:2024/06/10 11:06

内省

内省(Introspector)是Java语言对Bean类属性、事件的一种缺省处理方法。例如类A中有属性name,那我们可以通过getName,setName来得到其值或者设置新的值。通过getName/setName来访问name属性,这就是默认的规则。Java中提供了一套API用来访问某个属性的getter/setter方法,通过这些API可以使你不需要了解这个规则(但你最好还是要搞清楚),这些API存放于包java.beans中。一般的做法是通过类Introspector来获取某个对象的BeanInfo信息,然后通过BeanInfo来获取属性的描述器(PropertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后我们就可以通过反射机制来调用这些方法。
package introspector;import java.beans.*;import java.lang.reflect.Method;import org.junit.Test;public class Demo1 {    //使用内省api操作bean的属性    @Test    //获取全部属性    public void test1() throws Exception{        BeanInfo info=Introspector.getBeanInfo(Person.class); //得到bean自己的属性        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();  //即public void setAge(int age)        //执行方法        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());    }}
0 0
原创粉丝点击