PropertyDescriptor

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

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

最初感受这个方法没有具体的意义 ,既然我已经存在get ,set 方法 ,为什么要经过 PropertyDescriptor 反射来设置,通过分析以后,不少状况 ,咱们不单单要对一个对象 进行设置,可能会对多个不一样类型的对象进行设置,如此咱们就能够利用具体的方法名与PropertyDescriptor反射机制进行处理,具体代码以下  ip

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();
		}
	}
相关文章
相关标签/搜索