Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate constructor for required super fields

Tags:

java

lombok

I've the following class:

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public abstract class EmailData {

    private final Iterable<String> recipients;
}

and the following subclass:

import lombok.Getter;

@Getter
public class PasswordRecoveryEmail extends EmailData {

    private final String token;
}

Is there any possibility to annotate PasswordRecoveryEmail in such a way that a constructor for both required class and superclass fields will be generated?

like image 831
Opal Avatar asked Feb 15 '17 09:02

Opal


People also ask

Why do we generate constructor from superclass?

And creating constructors from a superclass can take even longer because the superclass can define multiple constructors that you need to reimplement. That is why Eclipse has two features to help you generate these constructor instantly: Generate Constructor using Field and Generate Constructor from Superclass.

Do super classes need constructors?

A subclass needs a constructor if the superclass does not have a default constructor (or has one that is not accessible to the subclass). If the subclass has no constructor at all, the compiler will automatically create a public constructor that simply calls through to the default constructor of the superclass.

Can we use this () and super () in a constructor?

“this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement). “this” can be passed as an argument in the method and constructor calls.

Does AllArgsConstructor call super?

AllArgsConstructor does not utilize superclass fields #1229.


1 Answers

The @…Constructor annotations will not explicitly call a constructor, so they all rely on a default constructor doing a proper job. So, no, you cannot convince Lombok to create these constructors for you.

The closest you can get it is to either:

  1. Provide a default constructor (no arguments) in EmailData that is protected and assigns some reasonable value to recipients.
  2. Write the required-args constructor for PasswordRecoveryEmail yourself.

Inheritance often is not quite covered by Lombok in my experience.

like image 78
Michael Piefel Avatar answered Oct 23 '22 08:10

Michael Piefel