使用注解生成equals/hashcode/toString [英] Generating equals / hashcode / toString using annotation

查看:70
本文介绍了使用注解生成equals/hashcode/toString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我在某个地方读到有人在编译时(使用 APT)通过确定哪些字段应该是哈希/相等测试的一部分来生成 equals/hashcode/toString 方法.我在网上找不到类似的东西(我可能做梦了吗?)...

可以这样做:

public class Person {@Id @GeneratedValue 私有整数 id;@Identity 私有字符串名字,姓氏;@Identity 私人日期 dateOfBirth;//...}

对于一个实体(所以我们想排除一些字段,比如 id).

或者像一个Scala案例类,即一个值对象:

@ValueObject公共类颜色{私有 int 红、绿、蓝;}

不仅文件变得更具可读性和更易于编写,而且还有助于确保所有属性都是 equals/hashcode 的一部分(以防您稍后添加另一个属性,而无需相应地更新方法).

我听说 IDE 对 APT 的支持不是很好,但我不认为这是一个主要问题.毕竟,测试主要由持续集成服务器运行.

知道这是否已经完成,如果没有,为什么?谢谢

解决方案

为此,我正在使用 Project Lombok.

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

解决方案

I'm using Project Lombok for this.

这篇关于使用注解生成equals/hashcode/toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆