How to ensure that child class will call the correct super constructor in lombok?

mr nooby noob :

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:

  • explicitly create my own all args constructor
  • in the child constructor, call all of the setters of the parent

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.

Jan Rieke :

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 @AllArgsConstructors, 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169198&siteId=1