java工具类复制类所有属性_对象属性拷贝工具类大全

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;

import org.springframework.beans.BeansException;

import org.springframework.beans.FatalBeanException;

import org.springframework.util.Assert;

import org.springframework.util.ClassUtils;/**

* @author LiJing

* @ClassName: BeanUtils

* @Description: 属性拷贝工具类

* @date 2018/4/10 11:54*/@Slf4jpublic classMyBeanUtils extends BeanUtils {/**

* 从org.springframework.beans.BeanUtils类中直接复制过来

*

* @param source

* @param target

* @throws BeansException*/

public static voidcopyProperties(Object source, Object target) throws BeansException {

copyProperties(source, target,null, (String[]) null);

}/**

* 从org.springframework.beans.BeanUtils类中直接复制过来,修改部分代码,不为null才复制

*

* @param source

* @param target

* @param editable

* @param ignoreProperties

* @throws BeansException*/

private static void copyProperties(Object source, Object target, Class>editable, String... ignoreProperties)

throws BeansException {

Assert.notNull(source,"Source must not be null");

Assert.notNull(target,"Target must not be null");

Class> actualEditable =target.getClass();if (editable != null) {if (!editable.isInstance(target)) {throw new IllegalArgumentException("Target class [" + target.getClass().getName() +

"] not assignable to Editable class [" + editable.getName() + "]");

}

actualEditable=editable;

}

PropertyDescriptor[] targetPds=getPropertyDescriptors(actualEditable);

List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;for(PropertyDescriptor targetPd : targetPds) {

Method writeMethod=targetPd.getWriteMethod();if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {

PropertyDescriptor sourcePd=getPropertyDescriptor(source.getClass(), targetPd.getName());if (sourcePd != null) {

Method readMethod=sourcePd.getReadMethod();if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {try{if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {

readMethod.setAccessible(true);

}

Object value=readMethod.invoke(source);//判断被复制的属性是否为null, 如果不为null才复制

if (value != null) {if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {

writeMethod.setAccessible(true);

}

writeMethod.invoke(target, value);

}

}catch(Throwable ex) {throw newFatalBeanException("不能拷贝属性 '" + targetPd.getName() + "' 从原对象给目标对象,详细原因见:", ex);

}

}

}

}

}

}/**

* 构造函数.*/

publicMyBeanUtils() {throw new RuntimeException("this is a util class,can not instance");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值