当没有最终字段时,Lombok注释@RequiredArgsConstructor
生成一个空构造函数,此代码编译时没有错误:
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class LombokTest {
public LombokTest(String a) {
// to avoid creation of the default constructor by the Java compiler
}
public static void main(String[] args) {
new LombokTest();
}
}
根据Lombok文档,注释@Data
也应生成RequiredArgsConstructor
,但在以下代码中
import lombok.Data;
@Data
public class LombokTest {
public LombokTest(String a) {
// to avoid creation of the default constructor by the Java compiler
}
public static void main(String[] args) {
new LombokTest();
}
}
main方法中的新LombokTest()会导致错误,因为no-arg构造函数未定义。
这是龙目岛的错误吗?
答案 0 :(得分:1)
我认为这不是龙目岛的一个错误。 如果将@Data放在类上,只有在没有任何其他构造函数时才会生成空构造函数。
如果在类上放置@AllArgsConstructor和@Data,则相同:由于将生成包含所有参数的构造函数,因此不会生成空构造函数。
您可以添加@NoArgsConstructor来生成空构造函数。