Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to @Nonnull again at the implementation?

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`
like image 687
Thomas Weller Avatar asked Mar 06 '15 08:03

Thomas Weller


People also ask

How does @nonNull work?

@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.

What is NotNull Java?

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.


Video Answer


1 Answers

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

like image 113
barfuin Avatar answered Sep 28 '22 06:09

barfuin