java bean对象属性复制,将一个对象的属性值赋值给另一个对象,对象之间的复制方法

注意依赖,springframework下的复制顺序为 (目标对象,新对象)
import org.springframework.beans.BeanUtils;

    public static void main(String[] args) {
        InterfaceCaseDO oldInterfaceCase = new InterfaceCaseDO();

        oldInterfaceCase.setCaseName("zhangsan");
        oldInterfaceCase.setId(1l);
        oldInterfaceCase.setSendBody("lis");
        oldInterfaceCase.setProtocol("wangsu");
        oldInterfaceCase.setUpdateUser("zhaoliu");

        InterfaceCaseDO newInterfaceCase = new InterfaceCaseDO();
        BeanUtils.copyProperties(oldInterfaceCase,newInterfaceCase);

        newInterfaceCase.setImId(1);
        System.out.println(newInterfaceCase.toString());
    }



特别注意,一定要注意看清楚自己的依赖,
如果是org.apache.commons.beanutils.BeanUtils
那么复制顺序为(新对象,目标对象)
import org.apache.commons.beanutils.BeanUtils;

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        InterfaceCaseDO oldInterfaceCase = new InterfaceCaseDO();

        oldInterfaceCase.setCaseName("zhangsan");
        oldInterfaceCase.setId(1l);
        oldInterfaceCase.setSendBody("lis");
        oldInterfaceCase.setProtocol("wangsu");
        oldInterfaceCase.setUpdateUser("zhaoliu");

        InterfaceCaseDO newInterfaceCase = new InterfaceCaseDO();
        BeanUtils.copyProperties(newInterfaceCase,oldInterfaceCase);

        newInterfaceCase.setImId(1);
        System.out.println(newInterfaceCase.toString());
    }

}

另外,比如对象复制时,想排除某个属性,可以使用springframework的复制方法,也就是第一种方法,在方法上加上额外的参数,如下

比如排除掉bean的id和name属性,就可以这样写
 BeanUtils.copyProperties(oldInterfaceCase,newInterfaceCase,new String[]{"id","name"});

也可以写成
 BeanUtils.copyProperties(oldInterfaceCase,newInterfaceCase, "id","name");
 
如果想指定新对象的属性,比如id,在下面添加一个set就行了
BeanUtils.copyProperties(oldInterfaceCase,newInterfaceCase, "id","name");
newInterfaceCase.setImId(1);
这样复制的新对象就可以指定值了
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值