简体   繁体   中英

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 ie 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

我正在使用Project Lombok

虽然Pojomatic不进行编译时字节码操作,但它确实支持轻松创建equals,hashCode和toString方法,使用注释来自定义其行为。

Google's solution in library AutoValue: https://github.com/google/auto/tree/master/value uses @AutoValue annotation + generation of sources before compilation.

Several competing solutions are discussed in the following presentation: https://docs.google.com/presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM