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

posted @   zhjh256  阅读(4151)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2016-08-10 mysql并发insert deadlock分析以及解决,无delete/update/for update
2016-08-10 mysql下一个版本应该且实现并不复杂增加的常用功能
2016-08-10 mysql root强密码的必要性max_allowed_packet被改成1024引起的风险
点击右上角即可分享
微信分享提示