JAVA字段复制工具 BeanUtils 的 copyProperties

常用工具-字段拷贝赋值

用于相同字段值的考培拷贝(不同字段解决方案请往下看)

BeanUtils的copyProperties()方法有四种重载方式
1.copyProperties(Object source, Object target)
2.copyProperties(Object source, Object target, Class<?> editable)
3.copyProperties(Object source, Object target, String… ignoreProperties)
4.copyProperties(Object source, Object target, @Nullable Class<?> editable, @Nullable String… ignoreProperties)

参数有四种:
1.Object source ——数据源(不可空)
2.Object target ——目标对象(不可空)
3.Class<?> editable ——目标对象的限制类型(是否instansof)
4.@Nullable String… ignoreProperties—— 需要忽略的字段(可空、可多个)

1.简单运用
import org.springframework.beans.BeanUtils;

public class myTestCopy(){
	//方法一.将旧用户对象中同名数据拷贝到新对象中
	BeanUtils.copyProperties(oldUser,newUser);
	
	//方法二.同1方法,并且People.isInstance(newUser)为true
	//否则将抛出异常:throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
	BeanUtils.copyProperties(oldUser,newUser,People.class);
	
	//方法三.同1方法,并且忽略字段"name"、"age"
	BeanUtils.copyProperties(oldUser,newUser,"name","age");
	
	//方法四.同2+3,不做赘述

}
2.加强运用

? 当我想拷贝不同名的值时该怎么办呢
可以建立中间对象做转换,还能省略上述忽略字段的繁琐

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;

/**
* 例:userId 为查询条件,object为我的目标对象
*/
 public Boolean perfectMyInformation(String userId, Object object){
        try {
        	//1.根据传入条件查询数据
            UserDo userDo = getUserInfoById(userId);
            if(ObjectUtils.isNotEmpty(userDo)){
                //中间工具对象,其中包含我想转换的字段(字段名称同目标对象)
                ZJUtil z = new ZJUtil();
				//2.1 赋值不同名字段
                z.setNewName(userDo.getName());
                //2.2 赋值同名字段
                BeanUtils.copyProperties(userDo,z);

				//3.将中间对象和目标对象 的同名值拷贝
                BeanUtils.copyProperties(z,object);
            }
            return true;
        } catch (BeansException e) {
            log.error("perfectMyInformation fault !");
            return false;
        }
    }
小结

· 利用只能转换同名方法自定义工具方法,能完成更多需求。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ywh22122

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值