在 Eclipse 中自动生成支持 @NonNull 注释的 equals 和 hashCode

发布于 2024-10-05 14:06:43 字数 1193 浏览 0 评论 0原文

有没有办法配置 Eclipse 自动生成 hashCodeequals 并感知 @NonNull 注释?目前,我的 Eclipse 生成的代码带有不必要的 null 检查,即使在标记为 @NonNull 的字段上也是如此。


请注意,FindBugs 将发出警告,指出这些空检查是多余的。当然我们可以添加 @edu.umd.cs.findbugs.annotations.SuppressWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") 到方法中,但这似乎破坏了 FindBugs 和 @NonNull 在第一个中的作用地方。

在我看来,最好的解决方案是让 Eclipse 了解 JSR 305 并相应地生成 equalshashCode 而无需 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2024-10-12 14:06:44

我认为这些空检查并不是不必要的。如果将它们排除在外,则 equalshashcode 会对未通过验证的对象产生错误行为,从而导致各种问题。

跟进

如果你仍然要到处检查 null 的话,@NonNull 注释有什么用呢?

注解的要点是声明有效实例的该属性中没有null,并允许基于该声明实现验证机制。

然而,没有什么要求实例始终有效。事实上,如果是这种情况,那么您在创建实例并将实例链接在一起时会遇到各种实现问题(例如)。

I would argue that the those null checks are not unnecessary. If they were left out, then equals and hashcode would misbehave on objects that don't pass validation, and that would cause all sorts of problems.

FOLLOWUP

Then what's the use of @NonNull annotations if you're still going to check for null everywhere anyway?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文