Better way to only use callsuper in @EqualsAndHashCode and @ToString?
Wouldn't simply
@ToString(callSuper = true, of = {})
work? Lombok knows nothing about the superclass fields (as this information is unavailable at the time it runs) and you can't include id
or exclude name
. All you can do is to make it call super.toString()
. When you include no fields at all, then you get something like
Employee(super=Resource(43, Larvalis, [email protected]))
which may or mayn't be what you want. You could instead write
public String toString() {
return getClass().getSimpleName()
+ super.toString().replaceFirst("^[^(]+", "");
}
so you'd get just
Employee(43, Larvalis, [email protected])
Update:
The of
parameter is obsolete in the meantime, see onlyExplicitlyIncluded
in @Datz's answer.
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).