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

一開發說項目報錯css

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 

緣由: 實際參數列表和形式參數列表長度不一樣,看報錯信息指向java

@Builder

奇怪了,怎麼builder會報錯?less

正文

看報錯信息說是匹配不到全參數的構造函數,由於項目用的是lombok,個人註解以下函數

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

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

  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類則是經過私有構造函數來實例化,默認是全參數的構造函數。this

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

相關文章
相關標籤/搜索