Lombok toBuilder() 方法是否创建字段的深层副本

我toBuilder()在对象实例上使用来创建构建器实例,然后使用 build 方法来创建新实例。原始对象有一个列表,新对象是否引用了同一个列表或它的副本?


@Getter

@Setter

@AllArgsConstructor

public class Library {


    private List<Book> books;


    @Builder(toBuilder=true)

    public Library(final List<Book> books){

         this.books = books;

    }


}


Library lib2  = lib1.toBuilder().build();

lib2 书籍会引用与 lib1 书籍相同的列表吗?


浮云间
浏览 235回答 3
3回答

慕勒3428872

是的,@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

沧海一幻觉

您可以使用一个简单的技巧手动制作集合的副本:&nbsp; &nbsp; List<Book> books = new ArrayList<>();&nbsp; &nbsp; Library one = new Library(books);&nbsp; &nbsp; Library two = one.toBuilder()&nbsp; &nbsp; &nbsp; &nbsp; .books(new ArrayList<>(one.getBooks))&nbsp; &nbsp; &nbsp; &nbsp; .build();&nbsp; &nbsp; System.out.println(one.getBooks() == two.getBooks()); // false, different refs

慕神8447489

实际上你可以做的是使用其他映射工具从现有对象创建一个新对象。例如com.fasterxml.jackson.databind.ObjectMapper&nbsp; &nbsp; @AllArgsConstructor&nbsp; &nbsp; public static class Book&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; private String title;&nbsp; &nbsp; }&nbsp; &nbsp; @NoArgsConstructor&nbsp; &nbsp; @AllArgsConstructor&nbsp; &nbsp; @Getter&nbsp; &nbsp; public static class Library&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; private List<Book> books;&nbsp; &nbsp; }&nbsp; &nbsp; ObjectMapper objectMapper = new ObjectMapper(); //it's configurable&nbsp; &nbsp; objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );&nbsp; &nbsp; objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );&nbsp; &nbsp; List<Book> books = new ArrayList<>();&nbsp; &nbsp; Library one = new Library( books );&nbsp; &nbsp; Library two = objectMapper.convertValue( one, Library.class );&nbsp; &nbsp; System.out.println( one.getBooks() == two.getBooks() ); // false, different refs它可以很容易地包装在一些实用方法中,以便在整个项目中使用,比如ConvertUtils.clone(rollingStones, Band.class)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java