spring的beanutils工具类_BeanCopy工具类 - BeanCopyUtils

核心使用Spring的org.springframework.beans.BeanUtils实现拷贝。

import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;

/**

* @author jfp

* @create 2020/11/19 15:04

* @desc BeanCopy工具

**/

public class BeanCopyUtils {

private BeanCopyUtils(){

// 防止实例化工具类

throw new AssertionError("No " + BeanCopyUtils.class.getName() + " instances for you !");

}

/**

* 描述: 封装BeanUtils.copyProperties, 实现类拷贝

* @param source 源对象

* @param targetClass 目标对象Class

* @param 目标对象

* @return

*/

public static T copyBean(Object source, Class targetClass){

if (source == null){

return null;

}

try {

T target = targetClass.getDeclaredConstructor().newInstance();

BeanUtils.copyProperties(source, target);

return target;

} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {

e.printStackTrace();

}

throw new BeanCopyException(source, targetClass);

}

private static class BeanCopyException extends RuntimeException{

public BeanCopyException(Object source, Class> targetClass) {

super("Bean Copy Error: source=>" + source.toString() + ", targetClass=>" + targetClass.toString());

}

}

}

pom.xml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值