BeanUtils工具类下copyProperties拷贝对象的用法
BeanUtils.copyProperties()的用法
- BeanUtils.copyProperties使用场景
- BeanUtils.copyProperties的具体方法
- 总结
BeanUtils.copyProperties使用场景
在开发过程中,我们通常会遇到要将1个对象的属性值,赋值给另一个对象,一般有2中方法:
1、一个一个去set每一个属性的值。
2、使用BeanUtils工具类下的copyProperties方法去实现。
因此当要把一个对象里面的全部属性或者部分属性赋值给另一个对象的时候,可以使用改方法,值得一提的是: BeanUtils是浅拷贝。
浅拷贝是调用子对象的set方法,并没有将所有属性拷贝。(也就是说,引用的一个内存地址)
BeanUtils.copyProperties的具体方法
org.springframework.beans下BeanUtils工具类,a的属性名和b的属性名必须相同才能赋值
//方法1
public static void copyProperties(Object source, Object target) throws BeansException {...}
BeanUtils.copyProperties(a,b) //将a属性的值赋值给b//方法2
public static void copyProperties(Object source, Object target, Class<?> editable) throws BeansException {...}
BeanUtils.copyProperties(a,b,b) //将a属性的值赋值给b,b为目标对象Employee employee = new Employee();
employee.setName("张三");
employee.setAge(12);
Student student = new Student();
BeanUtils.copyProperties(employee,student,Student.class);
System.out.println(student.getName()+student.getAge());
//结果:张三12//方法3
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {...}
BeanUtils.copyProperties(a,b,“属性a”)//将a赋值给b,但属性a不赋值BeanUtils.copyProperties(employee,student,"age");
//结果:张三0
org.apache.commons.beanutils下BeanUtils工具类
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {...}
BeanUtils.copyProperties(a,b) //将b属性的值赋值给a,复制后的2个Bean的同一个属性可能拥有同一个对象的ref,这个在使用时要小心,特别是对于属性为自定义类的情况其余涉及的方法 void BeanUtils.copyProperty(Object bean, String name, Object value) bean是指你将要设置的对象,name指的是将要设置的属性(写成”属性名”),value 要设置的值void BeanUtils.setProperty(Object bean, String name, Object value) bean是指你将要设置的对象,name指的是将要设置的属性(写成”属性名”), value 要设置的值String BeanUtils.getProperty或getSimpleProperty(Object bean, String name) 获取对应对象的属性值 返回值是string类型void BeanUtils.populate(Object bean,Map<String,? extends Object> properties)其中Map中的key必须与目标对象中的属性名相同,否则不能实现拷贝。Map BeanUtils.describe(Object bean) 获取描述,key是属性 value是值 还有class 相关信息void ConvertUtils.register(Converter converter , ..),当需要将String数据转换成引用数据类型(自定义数据类型时),需要使用此方法实现转换。
总结
不管是org.springframework.beans还是org.apache.commons.beanutils,都是利用的反射机制和API的封装完成了对属性的赋值,但要注意赋值时属性名要相同以及源对象和目标对象的位置。