1.org.apache.commons.beanutils.BeanUtils属性拷贝的本质使用反射。
2.org.springframework.beans.BeanUtils属性拷贝本质使用反射。
3.自己写的反射进行对象复制。
4.直接使用get、set方法复制。
5.cglib的BeanCopier。
|
次数 |
10 |
100 |
1000 |
10000 |
100000 |
1000000 |
1 |
总耗时 |
143 |
167 |
398 |
969 |
4029 |
18037 |
单次耗时 |
14.3 |
1.67 |
0.398 |
0.0969 |
0.04029 |
0.018037 | |
2 |
总耗时 |
239 |
222 |
503 |
434 |
340 |
427 |
单次耗时 |
23.9 |
2.22 |
0.503 |
0.0434 |
0.00340 |
0.000427 | |
3 |
总耗时 |
1 |
9 |
62 |
190 |
428 |
2377 |
单次耗时 |
0.1 |
0.09 |
0.062 |
0.0190 |
0.00428 |
0.002377 | |
4 |
总耗时 |
0 |
0 |
1 |
2 |
12 |
22 |
单次耗时 |
0 |
0 |
0.001 |
0.0002 |
0.00012 |
0.000022 | |
5 |
总耗时 |
142 |
128 |
179 |
195 |
297 |
475 |
单次耗时 |
14.2 |
1.28 |
0.179 |
0.0195 |
0.00297 |
0.000475 |
下面就是通过反射来完成对象属性copy的方法可以看出使用set、get是效率最高的一种方式,但是对于开发效率来说是比较低的。那么对于1000条以内的对象属性copy建议使用反射机制来完成 ,其实Apache和spring的底层都是用的反射。cglib是修改字节码。
/**
* @author SuZhenD
* @Title: com.auction.shop.common.util.ObjectCopyUtil.java
* @Description: 建议在1000个以内copy对象时使用
*/
public class ObjectCopyUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectCopyUtil.class);
/**
* @Description: 对象copy
* @Param: originObj:原对象 obj1:目标对象
*/
public static Object copyObj(Object originObj,Object targetObj) throws Exception{
try {
Class<?> classType=originObj.getClass();
Class<?> targetClassType=targetObj.getClass();
Object resultObj=targetClassType.newInstance();
//由于不知道源对象的具体属性和属性值,通过反射机制,先得到属性名称,再拼接字段得到属性对应的get,set方法
for(Field field:classType.getDeclaredFields()){
String getMethodName="get"+field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);
String setMethodName="set"+field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);
try {
Method getMethod=classType.getDeclaredMethod(getMethodName, new Class[]{});
Object value=getMethod.invoke(originObj, new Object[]{});
Method setMethod=targetClassType.getDeclaredMethod(setMethodName, new Class[]{field.getType()});
setMethod.invoke(resultObj, new Object[]{value});
}catch (NoSuchMethodException noSuchMethodException){
continue;
}
}
return resultObj;
}catch (Exception e){
LOGGER.error("ObjectCopyUtil copyObj error:{}",e);
throw new Exception("ObjectCopyUtil copyObj error:{}",e);
}
}
}