基于原型模式完成分层pojo之间拷贝。
Apache的BeanUtils,反射、
Apache的PropertyUtils,反射,
Spring的BeanUtils,反射
cglib的BeanCopier,动态代理性能好
public class BeanCopierUtils{
public static HashMap<String,BeanCopier> cacheMap=new HashMap<String,BeanCopier>();
public void copyproperties(Object source,Object target){
String cache= source.getclass().tostring()+target.getClass().tostring();
if(!cacheMap.contentKey(cache)){
synchronized(BeancopierUtils.class){
if(!cacheMap.containskey(cache)){
beancopier= Beancopier.create(source.getclass,target.getclass,false);
cacheMap.put(cache,beancopier);
}else{
beanCopier= cahceMap.get(cache);
}
}
}else{
beanCopier=cacheMap.get(cache);
}
beancopier.copy(source,target,null);
}
}
public class StudentVo { private String id; private String name; public <T> T clone(Class<T> tClass){ T target= null; try { target = tClass.newInstance(); BeanCopierUtils.copyproperties(this,target); } catch (Exception e) { e.printStackTrace(); } return target; } }
<!-- cglib的BeanCopier需要的依赖 --> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm-commons</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm-util</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency>