Spring中提供的属性拷贝的方法BeanUtils.copyProperties

BeanUtils.copyProperties通过java反射将类中当前属性字段对应的内容复制到另外一个类中

//内部都是调用下面的私有方法 
1. BeanUtils.copyProperties(Object source, Object target) throws BeansException {}
2.public static void copyProperties(Object source, Object target, String... ignoreProperties)
内部都是调用下面的私有方法,ignoreProperties可以是一组需要忽略复制的字符串
3.public static void copyProperties(Object source, Object target, Class<?> editable)
内部都是调用下面的私有方法,editable确定需要操作的目前对象类

案例:
1. 创建一个实体类
//lombok中的注解,省去添加settter和getter方法
@Data
public class Book {
    private String username;
    private String password;
    private String email;
    }


2. 创建被复制的实体类
//lombok中的注解,省去添加settter和getter方法
@Data
public class Book {
public class Book2 {
    private String username;
    private String password;
    private String email;
}

3. 测试
 public static void main(String[] args) {
        Book book = new Book();
        book.setEmail("[email protected]");
        book.setPassword("123456");
        book.setUsername("happygiraffe");
        Book2 book2 = new Book2();
        //添加了忽略username属性的赋值
        BeanUtils.copyProperties(book,book2,"username");

        System.out.println(book.toString());
        System.out.println(book2.toString());
    }
 4. 打印结果:
 Book{username='happygiraffe', password='123456', email='[email protected]'}
 Book2{username='null', password='123456', email='[email protected]'}    


猜你喜欢

转载自blog.csdn.net/m0_37779570/article/details/81094731