Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating equals / hashcode / toString using annotation

I believe I read somewhere people generating equals / hashcode / toString methods during compile time (using APT) by identifying which fields should be part of the hash / equality test. I couldn't find anything like that on the web (I might have dreamed it ?) ...

That could be done like that :

public class Person {
  @Id @GeneratedValue private Integer id;

  @Identity private String firstName, lastName;
  @Identity private Date dateOfBirth;

  //...
}

For an entity (so we want to exlude some fields, like the id).

Or like a scala case class i.e a value object :

@ValueObject
public class Color {
  private int red, green, blue;
}

Not only the file becomes more readable and easier to write, but it also helps ensuring that all the attributes are part of the equals / hashcode (in case you add another attribute later on, without updating the methods accordingly).

I heard APT isn't very well supported in IDE but I wouldn't see that as a major issue. After all, tests are mainly run by continuous integration servers.

Any idea if this has been done already and if not why ? Thanks

like image 751
Bruno Bieth Avatar asked Mar 29 '10 03:03

Bruno Bieth


People also ask

Does @data generate equals and hashCode?

@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 is the use of @EqualsAndHashCode?

The @EqualsAndHashCode annotation instructs the compiler to execute an AST transformation which adds the necessary equals and hashCode methods to the class. The hashCode() method is calculated using Groovy's HashCodeHelper class which implements an algorithm similar to the one outlined in the book Effective Java.

How hashCode () and equals () methods are used in Hashmap?

If you override the equals() method, then it is mandatory to override the hashCode() method. hashCode(): This is the method of the object class. It returns the memory reference of the object in integer form. The value received from the method is used as the bucket number.


2 Answers

I'm using Project Lombok for this.

like image 155
Yuri.Bulkin Avatar answered Sep 22 '22 02:09

Yuri.Bulkin


While Pojomatic does not do compile-time bytecode manipulation, it does support easy creation of equals, hashCode and toString methods, using annotations to customize their behavior.

like image 43
Ian Robertson Avatar answered Sep 21 '22 02:09

Ian Robertson