在 Eclipse 中自动生成支持 @NonNull 注释的 equals 和 hashCode
有没有办法配置 Eclipse 自动生成 hashCode
和 equals
并感知 @NonNull
注释?目前,我的 Eclipse 生成的代码带有不必要的 null
检查,即使在标记为 @NonNull
的字段上也是如此。
请注意,FindBugs 将发出警告,指出这些空检查是多余的。当然我们可以添加 @edu.umd.cs.findbugs.annotations.SuppressWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
到方法中,但这似乎破坏了 FindBugs 和 @NonNull
在第一个中的作用地方。
在我看来,最好的解决方案是让 Eclipse 了解 JSR 305 并相应地生成 equals
和 hashCode
而无需 null
检查(并且如果无论如何,它们都是 null
那么就这样吧,让 NullPointerException
自然抛出,因为发生了契约违规)。
除此之外,如果能够自定义由 Eclipse 生成的 equals 和 hashCode 模板也会很好。
相关问题
Is there a way to configure Eclipse to automatically generate hashCode
and equals
with awareness of @NonNull
annotations? Currently my Eclipse generates the code with unnecessary null
checks, even on fields that are marked @NonNull
.
Note that FindBugs will raise warnings that these null checks are redundant. Of course we can add@edu.umd.cs.findbugs.annotations.SuppressWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
to the methods, but that seems to undermine the role of FindBugs and @NonNull
in the first place.
It looks to me that the best solution is to have Eclipse be aware of JSR 305 and generate equals
and hashCode
accordingly without null
checks (and if they are null
anyway then so be it and let a NullPointerException
be thrown naturally, because a contract violation has occurred).
Short of that, having a way to customize the equals
and hashCode
template generated by Eclipse would also be nice.
Related questions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这些空检查并不是不必要的。如果将它们排除在外,则
equals
和hashcode
会对未通过验证的对象产生错误行为,从而导致各种问题。跟进
注解的要点是声明有效实例的该属性中没有
null
,并允许基于该声明实现验证机制。然而,没有什么要求实例始终有效。事实上,如果是这种情况,那么您在创建实例并将实例链接在一起时会遇到各种实现问题(例如)。
I would argue that the those null checks are not unnecessary. If they were left out, then
equals
andhashcode
would misbehave on objects that don't pass validation, and that would cause all sorts of problems.FOLLOWUP
The point of the annotation is to declare that a valid instance doesn't have a
null
in that attribute, and allow the validation mechanism to be implemented based on that declaration.However, nothing requires instances to be valid at all times. Indeed, if that was the case, then you'd run into all sorts of implementation problems (for example) while creating and linking instances together.