3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
是的,@Builder(toBuilder=true)注解不執(zhí)行對(duì)象的深層復(fù)制,只復(fù)制字段的引用。
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貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用一個(gè)簡(jiǎn)單的技巧手動(dòng)制作集合的副本:
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貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
實(shí)際上你可以做的是使用其他映射工具從現(xiàn)有對(duì)象創(chuàng)建一個(gè)新對(duì)象。
例如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
它可以很容易地包裝在一些實(shí)用方法中,以便在整個(gè)項(xiàng)目中使用,比如ConvertUtils.clone(rollingStones, Band.class)
添加回答
舉報(bào)