views:

191

answers:

3

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

+6  A: 

I'm using Project Lombok for this.

Yuri.Bulkin
A: 

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.

Ian Robertson
Interesting approach. Wonder what the performance impact is.
Bruno Bieth
+1  A: 

Hello, could anyone of you explain me what is the advantage of using pojomatic rather then EqualsBuilder for instances provided by the more known api Apache commons.lang?

Enrico Giurin
It keeps equals, hashcode (and toString) consistent and simple. When you add properties to your class you don't have to update them, the new properties get automatically added to the hash and equality (no risk to forget to update the methods).
Bruno Bieth