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

来源:互联网 发布:一键海淘 知乎 编辑:程序博客网 时间:2024/05/17 22:23

     说到对象属性拷贝作者脑海中第一反应就是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
原创粉丝点击