java中的内省(Introspector)

比如一个person类就是一个javabean.

一个bean的属性,有它的get/set方法来决定。

-----------------------------------------

得到bean的所有属性:

@Test
    public void test1() throws IntrospectionException{
        BeanInfo info=Introspector.getBeanInfo(Person.class,Object.class);//得到自己的属性
        PropertyDescriptor[] pds=info.getPropertyDescriptors();
        for(PropertyDescriptor pd:pds){
            System.out.println(pd.getName());
        }
    }

-----------------------------------------------

操作指定属性

@Test
//获取bean的指定属性:age
    public void test2() throws IntrospectionException, Throwable, IllegalArgumentException, InvocationTargetException{
        
        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)); 
    }

posted @ 2016-12-13 19:09  贱贱的小帅哥  阅读(148)  评论(0)    收藏  举报