Java 之 PropertyDescriptor

   PropertyDescriptor 描述了一个JavaBean 属性的一对访问方法即 getter和setter。

常用的构造方法是PropertyDescriptor(String propertyName,Class<?> beanClass);

propertyName就是属性的名称,beanClass就是这个属性对应属于哪个对象的Class.

/**
 *
 * @author zhangwei_david
 * @version $Id: PropertyDescriptorDemo.java, v 0.1 2015年5月25日 下午8:17:59 zhangwei_david Exp $
 */
public class PropertyDescriptorDemo {

    /**
     *
     * @param args
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String[] args) throws IntrospectionException, IllegalAccessException,
    IllegalArgumentException, InvocationTargetException {
        // bean的实例
        Form form = new PropertyDescriptorDemo().new Form();
        // 创建属性name 的PropertyDescriptor
        PropertyDescriptor pd = new PropertyDescriptor("name", form.getClass());
        // 获取属性的setter方法
        Method writer = pd.getWriteMethod();
        // 反射调用setter方法设置值
        writer.invoke(form, "TEST");
        // 输入setter以后的结果
        System.out.println(form.getName());
        // 获取getter方法
        Method reader = pd.getReadMethod();
        // 获取属性值
        String value = (String) reader.invoke(form);
        // 获取属性
        String name = pd.getName();

        System.out.println(name + "=" + value);

    }

    /**
     *
     *  测试表单
     *
     * @author zhangwei_david
     * @version $Id: PropertyDescriptorDemo.java, v 0.1 2015年5月25日 下午8:40:29 zhangwei_david Exp $
     */
    class Form {
        /**属性name**/
        private String name;

        /**
         * Getter method for property <tt>name</tt>.
         *
         * @return property value of name
         */
        public String getName() {
            return name;
        }

        /**
         * Setter method for property <tt>name</tt>.
         *
         * @param name value to be assigned to property name
         */
        public void setName(String name) {
            this.name = name;
        }

    }
}

 

输出的结果是:

TEST
name=TEST

可以发现,正确调用了setter和getter方法,如果将Form中的getter方法删除后运行的结果是什么呢?

Exception in thread "main" java.beans.IntrospectionException: Method not found: setName
	at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:110)
	at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:70)
	at com.cathy.demo.reflect.PropertyDescriptorDemo.main(PropertyDescriptorDemo.java:32)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值