自定义test之java对象属性拷贝简单实现

     说到对象属性拷贝作者脑海中第一反应就是spring和apache的beanUtils以及cglib的beanCopier,前者的实现原理是利用java的反射,后者是加了动态代理提高拷贝速度。下面是作者利用java反射实现的一个极简单的例子,仅供学习参考作用,有好多情况都没有处理。


static public void copy(Object source,Object target) throws NoSuchFieldException, SecurityException, IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Field[] sourceFields=source.getClass().getDeclaredFields();
Field[] targetFields=target.getClass().getDeclaredFields();

Map<String,String> fieldMap=new HashMap<String,String>();
List<Field> commonPropertyList=new ArrayList<Field>();
//for循环得到source,target的共同(type+name)属性
for(int i=0;i<sourceFields.length+targetFields.length;i++){
if(i<sourceFields.length){// 属性的类型+属性名作为map的key值
fieldMap.put(sourceFields[i].getType()+sourceFields[i].getName(), sourceFields[i].toString());
}else{
if(fieldMap.get(targetFields[i-sourceFields.length].getType()+targetFields[i-sourceFields.length].getName())!=null){
commonPropertyList.add(targetFields[i-sourceFields.length]);
}
}
}
//对公共属性进行拷贝
for(Field field:commonPropertyList){
try {
PropertyDescriptor pdSource = new PropertyDescriptor(field.getName(), source.getClass());
PropertyDescriptor pdTarget = new PropertyDescriptor(field.getName(), target.getClass());

Method sourceMethod = pdSource.getReadMethod();
Method targetMethod = pdTarget.getWriteMethod();

Object getValue = sourceMethod.invoke(source, new Object[]{});
targetMethod.invoke(target, getValue);
}catch (Exception e){
System.out.println("属性 "+field.getName()+" 出错! 异常信息:"+e.getClass()+e.getMessage());
}
}
}


代码基本思路是先拿到二者的公共属性,然后对公共属性进行值的获取和赋值。优缺点很明显,优点是省去了部分无效get、set方法的判断,直接对公共属性进行操作,缺点是对于get方法没有属性声明的字段不会拷贝。

    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值