Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.annotation: @Nullable vs @CheckForNull

What is the difference between the two? Both seem to mean that the value may be null and should be dealt with accordingly i.e. checked for null.

Update: The two annotations above are part of JSR-305/FindBugs: http://findbugs.sourceforge.net/manual/annotations.html

like image 727
vitaly Avatar asked Sep 06 '12 13:09

vitaly


People also ask

What is @nullable in javax?

Annotation Type NullableThe annotated element could be null under some circumstances. In general, this means developers will have to read the documentation to determine when a null value is acceptable and whether it is necessary to check for a null value.

What is the use of @nullable annotation?

The @NonNull/@Nullable annotation can put in front of functions as well to indicate the return value nullability. return null; // warn: 'null' is returned by the method ... Easy, right? Keep your Billion Dollar in your pocket and enjoy using this @Nullable and @NonNull.

What is the use of @nullable annotation in Java?

@Nullable The @Nullable annotation helps you detect: Method calls that can return null. Variables (fields, local variables, and parameters), that can be null.

What is @nullable in spring?

Annotation Type NullableA common Spring annotation to declare that annotated elements can be null under some circumstance. Leverages JSR-305 meta-annotations to indicate nullability in Java to common tools with JSR-305 support and used by Kotlin to infer nullability of Spring API.


1 Answers

I think it is pretty clear from the link you added: if you use @CheckForNull and the code that uses the value does not check for null, FindBugs will show it as an error.

FindBugs will ignore @Nullable.

In practice this annotation is useful only for overriding an overarching NonNull annotation.

Use @CheckForNull in the cases when the value must always be checked. Use @Nullable where null might be OK.

EDIT: it seems that @CheckForNull is not well supported at the moment, so I suggest avoiding it and using @NonNull (also see Which @NotNull Java annotation should I use?). Another idea would be to get in touch directly with the FindBugs developers, and ask their opinion about the inconsistency in the documentation.

like image 193
lbalazscs Avatar answered Sep 24 '22 18:09

lbalazscs