使用lombok的@Builder的注解的一個坑


一開發說項目報錯

java.lang.Long,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.Integer,java.lang.Integer,java.util.Date,java.util.Date,java.lang.Integer,java.lang.Integer,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.Integer 

原因: 實際參數列表和形式參數列表長度不同,看報錯信息指向

@Builder

奇怪了,怎么builder會報錯?

正文

看報錯信息說是匹配不到全參數的構造函數,因為項目用的是lombok,我的注解如下

  1. @Data
  2. @NoArgsConstructor
  3. @Builder

已經有默認構造參數了,怎么還會報錯?猜想難道builder默認用的是全參數構造函數?嘗試加了@AllArgsConstructor,果然好了。上網查了下資料

  1.  
    The builder annotation creates a so-called 'builder' aspect to the class that is annotated or the class that contains a member which is annotated with @Builder.
  2.  
    If a member is annotated, it must be either a constructor or a method. If a class is annotated, then a private constructor is generated with all fields as arguments (as if @AllArgsConstructor(AccessLevel.PRIVATE) is present on the class), and it is as if this constructor has been annotated with @Builder instead.
  3.  
     
  4.  
    The effect of @Builder is that an inner class is generated named TBuilder, with a private constructor. Instances of TBuilder are made with the method named builder() which is also generated for you in the class itself (not in the builder class).
  5.  
     
  6.  
    The TBuilder class contains 1 method for each parameter of the annotated constructor / method (each field, when annotating a class), which returns the builder itself. The builder also has a build() method which returns a completed instance of the original type, created by passing all parameters as set via the various other methods in the builder to the constructor or method that was annotated with @Builder. The return type of this method will be the same as the relevant class, unless a method has been annotated, in which case it'll be equal to the return type of that method.

發現它的實現方式是會對標注這個注解的類的所有成員變量,所以在使用@Builder構建的時候如果不顯式的對某變量賦值的話默認就是null,因為這個變量此時是在Builder
類里的,通過調用build()方法生成具體T類則是通過私有構造函數來實例化,默認是全參數的構造函數。

@Builder默認的實現方式是在類上添加@AllArgsConstructor(access = AccessLevel.PACKAGE)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM