工具类之org.springframework.beans.BeanUtils.copyPropeties

  1. 类所属
    BeanUtils.copyProperties的全路径名是:org.springframework.beans.BeanUtils.copyProperties
  2. 类作用
    进行对象之间属性的赋值,避免用过get、set方法一个个属性的赋值
  3. 方法体
     * Copy the property values of the given source bean into the target bean.
     * <p>Note: The source and target classes do not have to match or even be derived
     * from each other, as long as the properties match. Any bean properties that the
     * source bean exposes but the target bean does not will silently be ignored.
     * <p>This is just a convenience method. For more complex transfer needs,
     * consider using a full BeanWrapper.
     * @param source the source bean //源对象
     * @param target the target bean //目标对象
     * @throws BeansException if the copying failed //异常类型
     * @see BeanWrapper
     */
    public static void copyProperties(Object source, Object target) throws BeansException {
    	copyProperties(source, target, null, (String[]) null);
    }
    
  4. 用法
/**
 * @author wxj
 * @date 2021年07月30日 11:56
 */
@Data
public class Father {
   private String face; // 长相
   private String height; // 身高
   private Life life; // 生命
}
@Data
public class Life {
   private String status;
}
@Data
public class Son extends Father {
    private Life life;

    public static void main(String[] args) {
        Father zs = new Father();
        zs.setFace("张三");
        zs.setHeight("身高250");

        Life zsLife = new Life();
        zsLife.setStatus("活着");
        zs.setLife(zsLife);

        Son ls=new Son();
        BeanUtils.copyProperties(zs,ls);
        
        System.out.println("height:"+ls.getHeight()+"  face:"+ls.getFace()+"  life:"+ls.getLife());
    }
}
//控制台打印
height:身高250  face:张三  life:Life(status=活着)

可以看到Father和Lif类属性赋值给了Son

5.总结
BeansUtils.copyProperties通过调用set方法完成赋值,所有是浅拷贝

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值