使用注释生成 equals / hashcode / toString
我相信我在某处读到人们在编译时(使用 APT)通过确定哪些字段应该是哈希/相等测试的一部分来生成 equals/hashcode/toString 方法。我在网络上找不到类似的东西(我可能梦想过它?)...
可以这样做:
public class Person {
@Id @GeneratedValue private Integer id;
@Identity private String firstName, lastName;
@Identity private Date dateOfBirth;
//...
}
对于一个实体(所以我们想排除一些字段,比如 id)。
或者像 scala 案例类,即值对象:
@ValueObject
public class Color {
private int red, green, blue;
}
不仅文件变得更可读且更容易编写,而且还有助于确保所有属性都是 equals / hashcode 的一部分(以防您稍后添加另一个属性,而无需相应地更新方法)。
我听说 IDE 中对 APT 的支持不是很好,但我不认为这是一个主要问题。毕竟,测试主要是由持续集成服务器运行的。
知道这是否已经完成了吗?如果没有,为什么? 谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我为此使用 Project Lombok 。
I'm using Project Lombok for this.
虽然 Pojomatic 不进行编译时字节码操作,但它确实支持轻松创建 equals 、 hashCode 和 toString 方法,使用注释来自定义它们的行为。
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.
Google 在库 AutoValue 中的解决方案: https://github.com/google/auto/tree/master /value 使用@AutoValue注释+编译前生成源。
以下演示文稿讨论了几种竞争解决方案:https://docs.google.com /presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/编辑
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