欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PropertyDescriptor

程序员文章站 2022-05-24 09:18:11
...

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

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