java object copy_java 对象 copy ObjectCopyUtils | 学步园

import org.apache.log4j.Logger;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

import java.security.AccessController;

import java.security.PrivilegedAction;

/**

* 使用spring的BeanUtil.copyProperties来代替

*/

@Deprecated

public class ObjectCopyUtils {

private static Logger logger = Logger.getLogger(ObjectCopyUtils.class.getName());

private static Object source;

private static Object target;

private static ObjectCopyType objectCopyType;

public enum ObjectCopyType{

SOURCE_NOT_NULL,

TARGET_IS_NULL,

ALL

}

private ObjectCopyUtils(){

}

/**

* @param paramSource 源对象

* @param paramTarget 目标对象

* @param paramObjectCopyType 操作类型 0: 如果源对象的当前i的属性的值不为null,才copy过去. 1:如果目标对象的当前i的属性的值为null,才copy过去.2.默认,所有都copy过去

* @throws IllegalAccessException

* @throws IllegalArgumentException

*/

public static void copyProperties(Object paramSource, Object paramTarget, ObjectCopyType paramObjectCopyType){

source = paramSource;

target = paramTarget;

objectCopyType = paramObjectCopyType;

if(source==null || target==null || objectCopyType==null){

return;

}

AccessController.doPrivileged(

new PrivilegedAction() { //NOSONAR

public Object run() {

Class objClass = source.getClass();

Class tarClass = target.getClass();

// 通过target对象的class到obj的class中逐个扫描有无相同的field类型

Field[] tarFields = tarClass.getDeclaredFields();

for(int i=0; i

String fieldName = tarFields[i].getName();

try {

Field objField = objClass.getDeclaredField(fieldName);

objField.setAccessible(true);

tarFields[i].setAccessible(true);

Object sourceValue = objField.get(source);

Object tarValue = tarFields[i].get(target);

if(tarFields[i].getModifiers() >= Modifier.FINAL){

continue; //final 属性不能修改

}

switch (objectCopyType){

case SOURCE_NOT_NULL:

//如果源对象的当前i的属性的值不为空,才复制过去.

if(sourceValue != null){

tarFields[i].set(target, sourceValue);

}

break;

case TARGET_IS_NULL:

//如果目标对象的当前i的属性的值为空,才复制过去.

if(tarValue == null){

tarFields[i].set(target, sourceValue);

}

break;

default:

//所有复制过去

tarFields[i].set(target, sourceValue);

break;

}

} catch (Exception e) { //NOSONAR

logger.error("ObjectCopyUtils.class copyProperties error" , e);

continue;

}

}

return null;

}

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值