重写BeanUtils.copyProperties(复制对象属性方法)

复制对象属性时用到apache common-beanutils这个工具包中的

BeanUtils.copyProperties

但经测试100W次复制单一属性的对象用了2354豪秒,这是因为通过JDK的method.invoke去反射调用方法复制对象中的属性,用http://code.google.com/p/reflectasm/这个工具包可以提高性能

public class BeanUtils {
	
	private static Map<Class,MethodAccess> methodMap = new HashMap<Class,MethodAccess>();
	
	private static Map<String,Integer> methodIndexMap = new HashMap<String,Integer>();
	
	private static Map<Class,List<String>> fieldMap = new HashMap<Class,List<String>>();

	public static void copyProperties(Object desc,Object orgi){
		MethodAccess descMethodAccess = methodMap.get(desc.getClass());
		if(descMethodAccess == null){
			descMethodAccess = cache(desc);
		}
		MethodAccess orgiMethodAccess = methodMap.get(orgi.getClass());
		if(orgiMethodAccess == null){
			orgiMethodAccess = cache(orgi);
		}
		
		List<String> fieldList = fieldMap.get(orgi.getClass());
		for (String field : fieldList) {
			String getKey = orgi.getClass().getName() + "." + "get" + field;
			String setkey = desc.getClass().getName() + "." + "set" + field;
			Integer setIndex = methodIndexMap.get(setkey);
			if(setIndex != null){
				int getIndex = methodIndexMap.get(getKey);
				descMethodAccess.invoke(desc, setIndex.intValue(), orgiMethodAccess.invoke(orgi, getIndex));
			}
		}
		
		
	}
	
	private static MethodAccess cache(Object orgi){
		synchronized (orgi.getClass()) {
			MethodAccess methodAccess = MethodAccess.get(orgi.getClass()); 
			Field[] fields = orgi.getClass().getDeclaredFields();
			List<String> fieldList = new ArrayList<String>(fields.length);
			for (Field field : fields) {
				if(Modifier.isPrivate(field.getModifiers()) && ! Modifier.isStatic(field.getModifiers())){
					//非公共私有变量
					String fieldName = StringUtils.capitalize(field.getName());
					int getIndex = methodAccess.getIndex("get"+fieldName);
					int setIndex = methodAccess.getIndex("set"+fieldName);
					methodIndexMap.put(orgi.getClass().getName()+"."+"get"+fieldName, getIndex);
					methodIndexMap.put(orgi.getClass().getName()+"."+"set"+fieldName, setIndex);
					fieldList.add(fieldName);
				}
			}
			fieldMap.put(orgi.getClass(),fieldList);
			methodMap.put(orgi.getClass(), methodAccess);
			return methodAccess;
		}
	}
	
	
}

 

用此方法运行100W次,大约用时800毫秒,约相差3倍.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值