使用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)

猜你喜欢

转载自www.cnblogs.com/zhjh256/p/11333045.html