简体   繁体   English

使用注释生成equals / hashcode / toString

[英]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. 我相信我通过识别哪些字段应该是散列/相等测试的一部分来阅读在编译期间(使用APT)生成equals / hashcode / toString方法的人。 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). 对于一个实体(所以我们想要排除一些字段,比如id)。

Or like a scala case class ie a value object : 或者像scala案例类,即值对象:

@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). 不仅文件变得更易读和更容易编写,而且它还有助于确保所有属性都是equals / hashcode的一部分(如果您稍后添加其他属性,而不相应地更新方法)。

I heard APT isn't very well supported in IDE but I wouldn't see that as a major issue. 我听说APT在IDE中得不到很好的支持,但我不认为这是一个主要问题。 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. 图书馆AutoValue中的Google解决方案: https ://github.com/google/auto/tree/master/value在编译之前使用@AutoValue注释+生成源。

Several competing solutions are discussed in the following presentation: https://docs.google.com/presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/edit 以下演示文稿中讨论了几种竞争解决方案: https//docs.google.com/presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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