Better way to only use callsuper in @EqualsAndHashCode and @ToString?

Viewed 9196

I have class where I inheritage some fields, among them my id fields and those I difference on for the object. I am using lombok to generate my @EqualsAndHashCode and @ToString, but only want to use my super class's version, and exclude all fields in my class. I am wondering if there is a way to do that, without using the exclude and then add all fields.

My classes:

@EqualsAndHashCode(of = { "id" })
@ToString(of = { "id", "email", "name" })
@Data
public abstract class Resource {
    @Id
    private Integer id;

    private String name;

    private String email;
}

@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class Employee extends Resource {
    private Organisation organisation;

    private List<Skill> skills = new ArrayList<Skill>();
}

Here I will get organisation and skills in my ToString, Equals and HashCode.

To exclude them I can use:

@ToString(callSuper = true, exclude = { "organisation", "skills" })

However as I have more fields than the example, and there might come more in the future, I would prefer if I could exclude all except for the ones from my super class.

I can also add one field in with the of = {}.

Is there any better way to accomplish that?

2 Answers

I suggest using @ToString.Include / @EqualsAndHashCode.Include on the id field in the base class together with the class annotation @ToString(onlyExplicitlyIncluded = true) / @EqualsAndHashCode(onlyExplicitlyIncluded = true):

@ToString(onlyExplicitlyIncluded = true)
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public abstract class Resource {
    @Id
    @ToString.Include
    @EqualsAndHashCode.Include
    private Integer id;
    ...

The you can use @ToString(callSuper = true, onlyExplicitlyIncluded = true) / @EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true) on the child class(es):

@ToString(callSuper = true, onlyExplicitlyIncluded = true)
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class Employee extends Resource {
    ...

The advantages:

  • it is not necessary to explicitly set the annotations default values (of = {}) (see @maaartinus answer)
  • you can not forget to update the list of fields in the of = {...} / included = {...}lists
  • you avoid the of annotation attribute which probably soon will be deprecated (see Javadoc).
Related