亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Lombok toBuilder() 方法是否創建字段的深層副本

Lombok toBuilder() 方法是否創建字段的深層副本

浮云間 2023-02-23 14:43:28
我toBuilder()在對象實例上使用來創建構建器實例,然后使用 build 方法來創建新實例。原始對象有一個列表,新對象是否引用了同一個列表或它的副本?@Getter@Setter@AllArgsConstructorpublic 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 書籍相同的列表嗎?
查看完整描述

3 回答

?
慕勒3428872

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


查看完整回答
反對 回復 2023-02-23
?
滄海一幻覺

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


查看完整回答
反對 回復 2023-02-23
?
慕神8447489

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)



查看完整回答
反對 回復 2023-02-23
  • 3 回答
  • 0 關注
  • 270 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號