本人java小菜一枚,工作一年有余,深感自己知识匮乏,就会ctrl c v。近日部门来一大哥,让我见识到真正coder的威力,仿佛打开了新世界大门,看到不懂得在此一记。
BeanUtils是这个包里比较常用的一个工具类,这里只介绍它的copyProperties()方法。该方法定义如下:
public static void copyProperties(java.lang.Object dest,java.lang.Object orig) throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException
看了一些网上的博客,大致意思就是这个工具类是用来简化set方法。比如有一个Person类和一个personForm,正常来说写法一般都是
PersonForm personForm=(PersonForm)form;
Person person = new Person();
person.setAge(personForm.getAge());
person.setName(PersonForm.getName());
但是通过BeanUtils.copyProperties能够直接赋值,代码如下
PersonForm personForm=(PersonForm)form;Person person = new Person();
BeanUtils.copyProperties(person,personForm);
大概就是这样,但是这个方法虽然简单,耗费的时间貌似是要超过手动set,get的时间,所以还是慎用。还要注意的是,BeanUtils的copyProperties方法不能复制非public声明类的属性,只是在其中一片博客看到,还未尝试 。