Do I need to @Nonnull again at the implementation?

Thomas Weller picture Thomas Weller · Mar 6, 2015 · Viewed 7.7k times · Source

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?

  1. Interface @Nonnull, Implementation @Override
  2. Interface @Nonnull, Implementation @Override, @Nonnull
  3. Interface has no annotation, Implementation @Override,@Nonnull`

Answer

barfuin picture barfuin · Mar 11, 2015

Go for option 2:

  1. 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).