3 回答
TA贡献1848条经验 获得超6个赞
是的,@Builder(toBuilder=true)注解不执行对象的深层复制,只复制字段的引用。
List<Book> books = new ArrayList<>();
Library one = new Library(books);
Library two = one.toBuilder().build();
System.out.println(one.getBooks() == two.getBooks()); // true, same reference
TA贡献1824条经验 获得超5个赞
您可以使用一个简单的技巧手动制作集合的副本:
List<Book> books = new ArrayList<>();
Library one = new Library(books);
Library two = one.toBuilder()
.books(new ArrayList<>(one.getBooks))
.build();
System.out.println(one.getBooks() == two.getBooks()); // false, different refs
TA贡献1780条经验 获得超1个赞
实际上你可以做的是使用其他映射工具从现有对象创建一个新对象。
例如com.fasterxml.jackson.databind.ObjectMapper
@AllArgsConstructor
public static class Book
{
private String title;
}
@NoArgsConstructor
@AllArgsConstructor
@Getter
public static class Library
{
private List<Book> books;
}
ObjectMapper objectMapper = new ObjectMapper(); //it's configurable
objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );
List<Book> books = new ArrayList<>();
Library one = new Library( books );
Library two = objectMapper.convertValue( one, Library.class );
System.out.println( one.getBooks() == two.getBooks() ); // false, different refs
它可以很容易地包装在一些实用方法中,以便在整个项目中使用,比如ConvertUtils.clone(rollingStones, Band.class)
添加回答
举报