Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Lombok @Data override the existing toString and hashCode methods?

Tags:

java

lombok

Recently we started make use of Lombok features in our project. we have @Data annotation for the Domain object, due to this running with some exception thrown by hashCode() method provided by Lombok api. Later, when I added @Setter and @Getter instead of @Data, I didn't see any issues.

Question1: Does Lombok @Data override the existing methods in a class like hashCode() and toString()?

Question2: why is hashCode() making problems here?

like image 869
Lovababu Avatar asked Oct 29 '14 08:10

Lovababu


People also ask

Does @data include @toString?

@Data is a convenient shortcut annotation that bundles the features of @ToString , @EqualsAndHashCode , @Getter / @Setter and @RequiredArgsConstructor together: In other words, @Data generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans: getters for all fields, ...

What Lombok @data does?

What is Lombok Data annotation? Lombok Data annotation ( @Data ) Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor.

Does @data generate equals and hashCode?

The annotation @Data with inheritance produces the next warning: Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java. lang.

What is the difference between @data and @value in Lombok?

@Value is the immutable variant of @Data ; all fields are made private and final by default, and setters are not generated. The class itself is also made final by default, because immutability is not something that can be forced onto a subclass.


1 Answers

Yes, @Data implies @EqualsAndHashCode and @ToString. See the @Data documentation.

The generated hashCode() method will call the hashCode methods for all fields. So if one of the values of the fields throws an exception, so will this.

One other scenario is that you have circular object references: If one object has a field that contains an object that has a field that refers to the first object, invoking the hashCode method will trigger a StackOverflow.

Disclosure: I am one of the Lombok developers.

like image 163
Roel Spilker Avatar answered Oct 01 '22 02:10

Roel Spilker