使用Java的Introspector类操作JavaBean的属性

来源:互联网 发布:淘宝店推广策划报告 编辑:程序博客网 时间:2024/06/03 17:05

Introspector类是Java提供的操作JavaBean的属性的工具类


Introspector类操作JavaBean属性的示例:

JavaBean:Person

package com.test.introspector;/** * Person * @author xuhu * */public class Person{    //id    private int id;     //姓名    private String name;    //年龄    private int age;        public int getId()    {        return id;    }    public void setId(int id)    {        this.id = id;    }    public String getName()    {        return name;    }    public void setName(String name)    {        this.name = name;    }    public int getAge()    {        return age;    }    public void setAge(int age)    {        this.age = age;    }}


IntrospectorTest:

package com.test.introspector;import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import org.junit.Test;/** * 内省测试类 * @author xuhu * */public class IntrospectorTest{    private Person p = new Person();        /**     * 获取Person类所有属性     * @throws IntrospectionException      */    @Test    public void test1() throws IntrospectionException    {        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();        //输出Person类所有属性        for(PropertyDescriptor pd : pds)        {            System.out.println(pd.getName());        }    }        /**     * Person类属性赋值 方法1     * @throws IntrospectionException      * @throws InvocationTargetException      * @throws IllegalArgumentException      * @throws Exception      */    @Test    public void test2() throws Exception    {        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();        //创建Person对象        for(PropertyDescriptor pd : pds)        {            if("name".equals(pd.getName()))            {                Method method = pd.getWriteMethod();                method.invoke(p, "测试用户");            }        }                System.out.println(p.getName());    }        /**     * Person类属性赋值 方法2     * @throws Exception     */    @Test    public void test3() throws Exception    {        PropertyDescriptor pd = new PropertyDescriptor("name", Person.class);        Method method = pd.getWriteMethod();        method.invoke(p, "测试用户2");                System.out.println(p.getName());    }            /**     * Person类属性读取方法     * @throws Exception     */    @Test    public void test4() throws Exception    {        PropertyDescriptor pd = new PropertyDescriptor("name", Person.class);        Method method = pd.getWriteMethod();        method.invoke(p, "测试用户2");                method = pd.getReadMethod();        String str = String.valueOf(method.invoke(p, null));                System.out.println(str + "#");    }}



0 0
原创粉丝点击