由于业务需要,可能存在以下类似model,比如正式表 零时表
那么在很多时候,正式表的model的属性要copy到零时表中,有时候又涉及到对比,如果只涉及一次这种类似的操作,自己set也就无所谓,但类似业务多了,就需要抽象了,反射式比较好的方式,能抽象提取这些操作
用commons的beanUtils 与spring的工具类封装了一个BeanUtilss
public class BeanUtilss {
/**
* 该方法对比不同Bean实例中具有相同属性值是否相等,只对比neww中的属性
* @param neww--系统对象
* @param old--目标对象
*/
public static boolean isChange(Object neww,Object old) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
if(neww==null||old==null){
throw new IllegalArgumentException();
}
boolean chanage=false;
Map newwMap=new PropertyUtilsBean().describe(neww);
Map oldMap=new PropertyUtilsBean().describe(old);
newwMap.remove("class");
oldMap.remove("class");
for(Object key:newwMap.keySet()){
if(!equals(newwMap.get(key),oldMap.get(key))){
return true;
}
}
return chanage;
}
/**
* 该方法对比不同Bean实例中具有相同属性值是否相等,只对比neww中的属性
* old属性为neww属性加前缀在preFix
* @param neww--系统对象
* @param old--目标对象
*/
public static boolean isChange(Object neww,Object old,String PreFix) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
boolean chanage=false;
Map newwMap=new PropertyUtilsBean().describe(neww);
Map oldMap=new PropertyUtilsBean().describe(old);
newwMap.remove("class");
oldMap.remove("class");
for(Object key:newwMap.keySet()){
if(!equals(newwMap.get(key),oldMap.get(PreFix+key))){
return true;
}
}
return chanage;
}
/**
* spring的BeanUtils功能增强,增加属性规则,copy目标Bean属性加preFix
* @param orig
* @param dest
* @param PreFix
* @param ignoreProperties
*/
public static void CopyProperties(Object orig,Object dest,String PreFix,String[] ignoreProperties) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
Map<String,Object> newwMap=new PropertyUtilsBean().describe(orig);
newwMap.remove("class");
Map<String,Object> map=new HashMap<String,Object>();
for(String key:newwMap.keySet()){
map.put(PreFix+key, newwMap.get(key));
}
BeanUtils.copyProperties(map, dest, ignoreProperties);
}
private static boolean equals(Object orig,Object dest){
if(orig==null&&dest!=null){
return false;
}
if((orig instanceof String)&& (dest instanceof String)){
if(StringUtils.isEmpty((String)orig)&&StringUtils.isEmpty((String)dest))
return true;
}
return orig.equals(dest);
}
}