org.springframework.beans.BeanUtils.copyProperties(Object sourse,Object target),作用就是把两个对象中相同字段进行赋值。不一定是相同对象,只要两个对象中有相同的成员变量就可以赋值。
/**
* @author kavito
* @date 2019/6/24 15:28
*/
public class TestBeanUtils {
@Data
@AllArgsConstructor
@ToString
@NoArgsConstructor
class Person{
private String name;
private Integer age;
}
@Test
public void test(){
Person p1 = new Person("刘备", 30);
Person p2 = new Person("关羽", 25);
Person p3 = new Person("张飞", 20);
System.out.println("赋值前:"+p2);
BeanUtils.copyProperties(p1, p2);//将p1的值拷贝到p2去
System.out.println("赋值后:"+p2);
//集合类型赋值:将list的值赋值给newlist
//注意不能直接这样赋值,BeanUtils.copyProperties(list, newList)
List<Person> list = new ArrayList<Person>(){{
add(p1);
add(p2);
add(p3);
}};
List<Person> newList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Person p = new Person();
BeanUtils.copyProperties(list.get(i),p);
newList.add(p);
}
System.out.println(newList);
}
}
运行结果: