When using javax.annotation.Nullable
to mark methods as "potentially returning null
value", where to put the @Nullable
annotation? On the method, or return type?
Is there any technical difference, or is this strictly a style issue?
Style A:
@Nullable
public Object blah() { ... }
Style B:
public @Nullable Object blah() { ... }
This is strictly a style issue.
No matter where you write the annotation in the source code, the annotation is actually on the method. That's because of the @Target
meta-annotation on the definition of javax.annotation.Nullable
, which makes javax.annotation.Nullable
a method annotation. You are allowed to write the annotation in either location, because
the Java Language Specification grammar permits method annotations to be interspersed with method modifiers such as public
.
I consider it clearer to place the annotation before the return type. After all, it's the return type that is non-null. It doesn't make sense to say that a method itself is non-null.
Placing the annotation before the return type has another important benefit: your code is compatible with versions of Nullable
that are defined as type annotations. Type annotations were introduced in Java 8. They are more expressive than method annotations, and they enable more powerful checking. For example, the Nullable
annotations supported by Eclipse and the Checker Framework are type annotations.
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