While I think there should be a general rule for inheriting annotations or not, I'm specifically interested in making FindBugs recognize my rules, so this question is FindBugs specific.
AFAIK, JavaDoc comments are taken from the interface and are ignored at the implementation. Does this concept also apply to annotations like @Nonnull
(or @NotNull
)?
Given the @Override
annotation, it is at least possible to add additional annotations which are not present at the interface.
What will happen in the following cases? Will FindBugs recognize all of them? Which one is the preferred one regarding clean code?
@Nonnull
, Implementation @Override
@Nonnull
, Implementation @Override
, @Nonnull
@Override,
@Nonnull`@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
notNull() is a static method of the Validate class that is used to check whether the passed object is null or not. If the passed object is null , then the method raises an exception with a formatted message. If the passed object is not null , then the method returns the input as it is.
Go for option 2:
- Interface @Nonnull, Implementation @Override @Nonnull
FindBugs and many other tools such as IDEs do a much better job if they find the annotations in the right places. These annotations are not inherited, as the JLS states at the bottom of this section:
Annotation inheritance only works on classes (not methods, interfaces, or constructors)
So the tools would need to go looking for them on their own. Which some tools do, but even FindBugs does not do it consistently (last I checked).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With