两种BeanUtils不同与简单用法

两种BeanUtils不同与用法

来自:https://www.cnblogs.com/ahri-gx/p/10551340.html
1)两者的copyProperties方法参数位置不同

org.springframework.beans.BeanUtils:  copyProperties(sourceDemo, targetDemo)

org.apache.commons.beanutils.BeanUtils:  copyProperties(targetDemo, sourceDemo)

2)要求两个Bean的属性名相同,且有对应的setXxx方法和getXxx方法。其实底层原理是使用sourceDemo的getXxx方法和targetDemo的setXxx方法

3)sourceDemo有的属性而targetDemo没有的属性,不会封装到targetDemo对象中;

targetDemo有的属性而sourceDemo没有的属性,会封装到targetDemo中,数据为默认值(注意基本类型默认值与引用类型默认值不同)

4)类型转换问题

a)基本类型与其对应的封装类型可以相互转换

b)org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils对于String和Date类型转换的情况是不同;
  日期可以查看这个:https://blog.csdn.net/qidasheng2012/article/details/84562732

spring的:

  public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
  SourceDemo sourceDemo = new SourceDemo();
        sourceDemo.setId(10);
        sourceDemo.setName("姓名");
        sourceDemo.setAddress("地址");
        sourceDemo.setCreateTime(new Date());
        
        TargetDemo targetDemo = new TargetDemo();
        BeanUtils.copyProperties(sourceDemo, targetDemo);
        System.out.println(targetDemo);
        
        org.apache.commons.beanutils.BeanUtils.copyProperties(targetDemo, sourceDemo);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值