Java Lombok: Omitting one field in @AllArgsConstructor?

三世轮回 提交于 2020-01-12 03:55:07

问题


If I specify @AllArgsConstructor using Lombok, it will generate a constructor for setting all the declared (not final, not static) fields. Is it possible to omit some field and this leave generated constructor for all other fields?


回答1:


No that is not possible. There is a feature request to create a @SomeArgsConstructor where you can specify a list of involved fields.

Full disclosure: I am one of the core Project Lombok developers.




回答2:


Alternatively you could use @RequiredArgsConstructor. This adds a constructor for all fields that are either @NonNull or final.

See documentation




回答3:


A good way to go around it in some cases would be to use the @Builder




回答4:


You can initialise those particular fields with some default values or null and then create the constructor omitting those fields. But remember, now you can't pass the omitted fields in the constructor anymore.

@AllArgsConstructor
Public class MyClass{
        @JsonProperty
        String omitThisField = null;
        @JsonProperty
        String reqField1;
        @JsonProperty 
        String reqField2;
}

MyClass myClass = new MyClass("req field1", "req field2");

But this won't work now:

//MyClass myClass = new MyClass("omitted field", "req field1", "req field2");


来源:https://stackoverflow.com/questions/23761242/java-lombok-omitting-one-field-in-allargsconstructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!