之前项目里面一直在用dozer,后来遇到性能瓶颈问题,一查看发现dozer复制一个对象居然用了0.2秒 看来是不能用了,dozer 虽然强大,但我用的都只是很简单的功能,就对象的复制转换,于是就自己用反射写了个复制方法,结果发现性能提升了好多好多。。
话不多说,上代码,下面是方法的代码:
/**
* 深度copy。自动转换带下划线的属性根java驼峰格式属性。
* 例子:见下面注释掉的main方法
*/
public class SimpleCopyUtil {
public static <T> T copy(Object obj,Class<T> toObj)throws Exception{
T toObjIns = (T)toObj.newInstance(); //创建目标对象实例
Class sourCls = obj.getClass();
//遍历源属性
do{
Field[] sourFlds = sourCls.getDeclaredFields(); //源属性集
for(int i = 0 ; i < sourFlds.length; i++){ //遍历源所有属性
Field sf = sourFlds[i];
sf.setAccessible(true);
//遍历目标所有属性
Class toCls = toObj;
do{
Field[] toFlds = toCls.getDeclaredFields(); //源属性集
for(int j = 0 ; j < toFlds.length; j++){ //遍历源所有属性
Field tof = toFlds[j];
tof.setAccessible(true);
if(sf.getName().equals(tof.getName())){
String rightType = tof.getType().toString();//得到此属性的类型
String leftType = sf.getType().toString();
if(StringUtils.equals(rightType,leftType)){
//基本数据类型
if(sf.getType().isPrimitive() || leftType.endsWith("String") || leftType.endsWith("Date")){
tof.set(toObjIns,sf.get(obj));
} else {
//自定义格式,递归实现
Object leftAttribute = sf.get(obj);
Object rightAttribute = copy(leftAttribute,tof.getType());
tof.set(toObjIns,rightAttribute);
}
}
}
}
toCls = toCls.getSuperclass();
}while(toCls != Object.class);
}
sourCls = sourCls.getSuperclass();
}while(sourCls != Object.class);
return toObjIns;
}
public static void main(String[] args) throws Exception{
@Data
@AllArgsConstructor
class CA{
public CA(){}
private String nameTable;
private String addressTable;
}
@Data
@AllArgsConstructor
class C{
public C(){}
private String nameTable;
private String addressTable;
private CA caTest;
}
@Data
@AllArgsConstructor
class A{
public A(){}
private String nameTable;
private String addressTable;
private C cTest;
}
@Data
@AllArgsConstructor
class B{
public B(){}
private String nameTable;
private String addressTable;
private C cTest;
}
B b = new B("name","address",new C("c1","c2",new CA("ca1","ca2")));
A a = copy(b,A.class);
System.out.println(a);
}
}
附录一张我自己测试的结果图: