开发者

Automatically generating equals and hashCode in Eclipse that is aware of @NonNull annotations

开发者 https://www.devze.com 2023-01-28 15:54 出处:网络
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

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 30开发者_如何学C5 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

  • make Eclipse equals() / hashCode() use getters
  • Is it possible to make eclipse generate hashCode and equals with HashCodeBuilder and EqualsBuilder


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号