注意是org.springframework.beans.BeanUtils包下的BeanUtils
1、首先定义两个bean分别取名为Bean1和Bean2,如下:
Bean1下的内容:
import lombok.Data;
@Data
public class Bean1 {
private Integer age;
private String name;
private Integer score;
}
Bean2下的内容:
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class Bean2 {
private Integer age;
private String name;
private LocalDateTime localDateTime;
}
2、定义一个测试类MyTest,代码如下:
import org.springframework.beans.BeanUtils;
import java.time.LocalDateTime;
public class MyTest {
public static void main(String[] args) {
Bean1 bean1 = new Bean1();
bean1.setAge(1);
bean1.setName("jjw");
bean1.setScore(60);
Bean2 bean2 = new Bean2();
BeanUtils.copyProperties(bean1,bean2);
bean2.setLocalDateTime(LocalDateTime.now());
System.out.println(bean2);
}
}
输出结果:
Bean2(age=1, name=jjw, localDateTime=2023-06-25T15:56:24.704)
结论:
将bean1的属性的值拷贝到bean2与之对应的字段上,如果字段名字不相同则不拷贝。