使用注释生成 equals/hashcode/toString [英] Generating equals / hashcode / toString using annotation
问题描述
我相信我在某个地方读到有人在编译时(使用 APT)通过确定哪些字段应该是哈希/相等测试的一部分来生成 equals/hashcode/toString 方法.我在网上找不到类似的东西(我可能做梦了吗?)...
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 ?) ...
可以这样做:
public class Person {
@Id @GeneratedValue private Integer id;
@Identity private String firstName, lastName;
@Identity private Date dateOfBirth;
//...
}
对于一个实体(所以我们想排除一些字段,比如 id).
For an entity (so we want to exlude some fields, like the id).
或者像一个Scala案例类,即一个值对象:
Or like a scala case class i.e a value object :
@ValueObject
public class Color {
private int red, green, blue;
}
不仅文件变得更易读和更容易编写,而且还有助于确保所有属性都是 equals/hashcode 的一部分(以防您稍后添加另一个属性,而无需相应地更新方法).
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).
我听说 IDE 不太支持 APT,但我不认为这是一个主要问题.毕竟,测试主要由持续集成服务器运行.
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.
这篇关于使用注释生成 equals/hashcode/toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!