PropertyDescriptor

 今天下午在看公司的代码的时候看到这样一段,

PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
     1.  getReadMethod(),获得用于读取属性值的方法
     2.  getWriteMethod(),获得用于写入属性值的方法

最初感觉这个方法没有具体的意义 ,既然我已经存在get ,set 方法 ,为何要通过 PropertyDescriptor 反射来设置,经过分析之后,很多情况 ,我们不仅仅要对一个对象 进行设置,可能会对多个不同类型的对象进行设置,如此我们就可以利用具体的方法名与PropertyDescriptor反射机制进行处理,具体代码如下  

	
public static void setWithConflictDetection(Object target, String propertyName, String param) {
		PropertyDescriptor pd = null;
		try {
			pd = new PropertyDescriptor(propertyName, target.getClass());
		} catch (IntrospectionException e) {
			e.printStackTrace();
			throw new InvalidParameterException("No such property: " + propertyName);
		}
		Method methodGet = pd.getReadMethod();
		Method methodSet = pd.getWriteMethod();
		try {
			Object oldValue  = methodGet.invoke(target, new Object[]{});
			if(oldValue!=null && param!=null && !oldValue.equals(param)) {
				throw new InvalidParameterException(propertyName, oldValue+"", param);
			}else if(param != null){
				methodSet.invoke(target, param);
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

 

转载于:https://my.oschina.net/u/198077/blog/1603113

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值