Inheritance with lombok annotation get errors

我与影子孤独终老i 提交于 2021-01-27 04:58:22

问题


In my project, lombok is used to avoid writing getters and setters for a class. I have two classes Child extends Parent:

@Value
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Parent {
    @Nonnull
    @JsonProperty("personId")
    private final String personId;

    @JsonProperty("personTag")
    private final String personTag;
    ...
}

And

@Value
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Child extends Parent {
    @Nonnull
    @JsonProperty("childId")
    private final String childId;
    ...
}

But this doesn't seems work as no default constructor available in Parent. I'm not familiar with the lombok annotation. Is there any good way to extend the Base class and use the lombok annotation at the same time?


回答1:


Class hierarchies + lombok doesn't work particularly well, in the sense that the lombok operations done on your Child class don't know anything about parent.

However, your specific question seems answerable:

The Parent class has a constructor that takes all fields, because you asked lombok to make this constructor via @AllArgsConstructor. Therefore, it does not have a no-args constructor. If you want both constructors (the one that takes all fields + a second one that takes no arguments, a.k.a. the default constructor), also add a @NoArgsConstructor annotation to tell lombok that you want that.

NB: @Builder does not work with hierarchy either, but the fresh new @SuperBuilder feature does. I'm pretty sure you want to replace @Builder with @SuperBuilder here. SuperBuilder requires that ALL classes in the hierarchy are annotated with @SuperBuilder and not @Builder.




回答2:


TL;DR: add @NonFinal annotation to your superclass

Details: @Value annotation makes the class final, so you cannot inherit from it. Experimental @NonFinal annotation should prevent this.

import lombok.Value;
import lombok.experimental.NonFinal;

@Value
@NonFinal
public class Parent {

REF: https://projectlombok.org/features/Value



来源:https://stackoverflow.com/questions/52341050/inheritance-with-lombok-annotation-get-errors

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