您的位置:首页 > 编程语言 > Java开发

java不同类型对象之间的拷贝

2011-06-23 11:29 459 查看
场景:

    1.我所谓的拷贝不是克隆

    2.是不同类型但是有相同属性名,属性与属性之间类型可以不同



思路:

    1.最容易想的就是反射,这边get,那边set,对的

    2.利用commons的beanutils包,更容易处理,它有现成的第一层拷贝,我们利用一下,递归拷贝无数层

 

实现:注意看依赖哪些包和类哦

   
package com.core.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;

/**
* 对象与对象深度拷贝,包括嵌套的复合类型,可以忽略类型,只要有相通的属性名
* 数组也可以处理,即便dest是一个空数组
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2011</p>
* @author 郑未
* @version 1.0
*/
public class BeanUtils {
private static final Logger LOG = Logger.getLogger(BeanUtils.class);
/**
*
* @param dest 目标对象
* @param orig 原始对象
* @throws Exception
*/
public static void copy(Object dest, Object orig) throws Exception {
if (dest == null) {
throw new IllegalArgumentException("No destination bean specified");
}
if (orig == null) {
throw new IllegalArgumentException("No origin bean specified");
}

Class origClass = orig.getClass();
Class destClass = dest.getClass();
if (origClass == String.class || origClass.isPrimitive()) {
dest = orig;
}
if(orig.getClass().isArray()){
Object[] destArr = (Object[]) dest;
Object[] origArr = (Object[]) orig;
Class elemenClass = destArr.getClass().getComponentType();

for(int i=0;i<origArr.length;i++){
if(destArr[i]==null){
destArr[i] = elemenClass.newInstance();
}

copy(destArr[i], origArr[i]);
}
}
String classLogInfo = "origClass:"+origClass.getName()+",destClass:"+destClass.getName()+",";
PropertyDescriptor[] origDescriptors = PropertyUtils
.getPropertyDescriptors(orig);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if ("class".equals(name)) {
continue;
}
Object value = null;
if (PropertyUtils.isReadable(orig, name)
&& PropertyUtils.isWriteable(dest, name)) {
try {
value = PropertyUtils.getSimpleProperty(orig, name);
PropertyUtils.setSimpleProperty(dest, name, value);
} catch (IllegalArgumentException e) {
// 类型不同
try {
PropertyDescriptor targetDescriptor = PropertyUtils
.getPropertyDescriptor(dest, name);
Object new_value = targetDescriptor.getPropertyType()
.newInstance();
copy(new_value, value);
//						LOG.info(new_value);
PropertyUtils.setSimpleProperty(dest, name, new_value);
}catch(IllegalArgumentException e1){
//
}
catch (IllegalAccessException e1) {
throw e1;
} catch (InvocationTargetException e1) {
throw e1;
} catch (NoSuchMethodException e1) {
throw e1;
} catch (InstantiationException e1) {
throw e1;
}
} catch (NoSuchMethodException e) {
throw e;
} catch (IllegalAccessException e) {
throw e;
} catch (InvocationTargetException e) {
throw e;
}
}
}
}

}


说明:

    抛砖引玉,可能还考虑不周全,烦请大家测试并提出建议
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息