JAVA Introspector内省用法

来源:互联网 发布:网络博客正规吗 编辑:程序博客网 时间:2024/06/05 11:43
package cn.itcat.introspector;import java.beans.BeanInfo;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); // 得到bean自己的属性        PropertyDescriptor[] pds = info.getPropertyDescriptors();        for (PropertyDescriptor p : pds) {            System.out.println(p.getName());        }    }    // 操纵bean的指定属性    @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());    }}
0 0
原创粉丝点击