问题
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