现在的位置: 首页 > 综合 > 正文

深入java对象复制的分析

2012年08月03日 ⁄ 综合 ⁄ 共 1328字 ⁄ 字号 评论关闭

java本身提供了对象复制的能力,在java.lang.Object类中有clone方法,该方法是一个protected方法,在子类需要重写此方法并声明为public类型,而且还需实现Cloneable接口才能提供对象复制的能力,clone()是一个native方法,native方法的效率一般来说都是远高于java中的非native方法,对性能比较关心的话首先考虑这种方式,这种复制在网上有很多例子就不多写了;在这要用的另一种方式——通过java的反射机制复制对象,这种方式效率可能会比clone()低,而且不支持深度复制以及复制集合类型,但通用性会提高很多,下边是进行复制的代码:

复制代码 代码如下:
private <T> T getBean(T TargetBean, T SourceBean) {
if (TargetBean== null) return null;
Field[] tFields = TargetBean.getClass().getDeclaredFields();
Field[] sFields = SourceBean.getClass().getDeclaredFields();
try {
for (Field field : tFields ) {
String fieldName = field.getName();
if (fieldName.equals("serialVersionUID")) continue;
if (field.getType() == Map.class) continue;

if (field.getType() == Set.class) continue;

if (field.getType() == List.class) continue;
for (Field sField : sFields) {
if(!sField .getName().equals(fieldName)){
continue;
}
Class type = field.getType();
String setName = getSetMethodName(fieldName);
Method tMethod = TargetBean.getClass().getMethod(setName, new Class[]{type});
String getName = getGetMethodName(fieldName);
Method sMethod = SourceBean.getClass().getMethod(getName, null);
Object setterValue = voMethod.invoke(SourceBean, null);
tMethod.invoke(TargetBean, new Object[]{setterValue});
}
}
} catch (Exception e) {
throw new Exception("设置参数信息发生异常", e);
}
return TargetBean;
}

该方法接收两个参数,一个是复制的源对象——要复制的对象,一个是复制的目标对象——对象副本,当然这个方法也可以在两个不同对象间使用,这时候只要目标对象和对象具有一个或多个相同类型及名称的属性,那么就会把源对象的属性值赋给目标对象的属性。

抱歉!评论已关闭.