BeanUtils.copyProperties()
-
特点:
- 提供了一个简单的方式来复制一个JavaBean的属性到另一个JavaBean中。
- 适合于结构相似且属性名相同的对象之间的属性复制操作。
- 使用方便,通过静态方法直接调用即可完成属性的复制。
-
// 假设有两个类,SourceBean和DestinationBean,它们具有相同的属性 public class SourceBean { private String name; private int age; // 省略getter和setter } public class DestinationBean { private String name; private int age; // 省略getter和setter } // 使用BeanUtils.copyProperties进行属性复制 SourceBean source = new SourceBean(); source.setName("John"); source.setAge(30); DestinationBean destination = new DestinationBean(); BeanUtils.copyProperties(destination, source); // 现在destination中的属性已经复制了source的属性 System.out.println(destination.getName()); // 输出 "John" System.out.println(destination.getAge()); // 输出 30
-
Builder 模式
-
特点:
- 一种创建对象的设计模式,通过链式调用方法设置对象的属性,最后通过
build()
方法构建对象。 - 适合于需要构建复杂对象,或者对象具有多个可选属性和复杂初始化逻辑的情况。
- 提供了更多的灵活性和控制能力,可以在构建过程中进行逻辑判断和属性设置。
- 一种创建对象的设计模式,通过链式调用方法设置对象的属性,最后通过
-
// 假设有一个复杂的对象需要创建,例如一个包含多个属性的用户对象 public class User { private String name; private int age; private String address; private String phoneNumber; // 使用Builder模式来构建User对象 public static class Builder { private String name; private int age; private String address = ""; private String phoneNumber = ""; public Builder(String name, int age) { this.name = name; this.age = age; } public Builder address(String address) { this.address = address; return this; } public Builder phoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } public User build() { return new User(this); } } private User(Builder builder) { this.name = builder.name; this.age = builder.age; this.address = builder.address; this.phoneNumber = builder.phoneNumber; } // 省略getter方法 } // 使用Builder模式创建User对象 User user = new User.Builder("Alice", 25) .address("123 Main St") .phoneNumber("555-1234") .build();
区别和适用场景
-
区别:
BeanUtils.copyProperties()
适用于简单的属性复制,两个类结构相似且属性名一致的情况。- Builder模式适用于构建复杂对象,或者需要设置多个可选属性的对象,提供了更多的灵活性和控制能力。
-
适用场景:
- 使用
BeanUtils.copyProperties()
来简化类之间的属性复制操作,例如在DTO(Data Transfer Object)和实体类之间。 - 使用Builder模式来创建复杂对象,尤其是当对象具有多个可选属性或者需要在构建过程中进行逻辑判断和初始化设置时。
- 使用