注意依赖,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);
这样复制的新对象就可以指定值了