Reputation: 2253
Say that I have the following classes
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class A {
private String item1;
private String item2;
private String item3;
}
and
@Data
public class B extends A {
private String item4;
@Builder(builderMethodName = "bBuilder")
public B(String item1, String item2, String item3, String item4) {
super(item1, item2, item3);
this.item4 = item4;
}
}
how can I (or is there even a way) to guarantee that the child constructor will call the "correct" constructor when I call the super constructor? More specifically, I want to 100% ensure that the three string values I pass in indeed are set to the correct fields in the parent, and not something where, say, item1 in is set to item2.
I know that I could, for example either:
but I am just curious if Lombok is smart enough, somehow, to set the the fields in the child class to the correct ones in the parent class?
Edit:
I know that the order of the fields determine the order of the fields of the constructor, but that to me isn't safe enough, since if someone inserts a new field, say in the middle, then it will throw everything off.
However, perhaps the @SuperBuilder might be something that I could use, as some have suggested, if not, then I will just explicit create my own constructor to guarantee the order of fields.
Upvotes: 2
Views: 4878
Reputation: 8042
The order of the parameters of an @AllArgsConstructor
matches the order of the fields in the source code. So right now you are safe.
However, if you later modify the order of the fields in A
(or rename them), you will get wrong assignments (or wrong parameter names in your builder), but no compiler error.
But there is an easy way out: Use @SuperBuilder
, and remove @Data
. (Note that you need @SuperBuilder
on all classes in your hierarchy.) You won't get @AllArgsConstructor
s, changes to the field order are irrelevant, and name changes are immediately reflected in the builder classes.
If that is not possible, your only choice is to put a big fat warning comment into A
advising later coders not to mess around with the names and order.
Upvotes: 2