@Nullable annotation usage
I saw some method in java declared as:
void foo(@Nullable Object obj)
{ ... }
What's the meaning of @Nullable
here? Does it mean the input could be null
? Without the annotation, the input can still be null, so I guess that's not just it?
Thanks
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
This annotation is commonly used to eliminate NullPointerExceptions
. @Nullable
is often says that this parameter might be null
. Good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you tell that this dependency might be null
. If you would try to pass null
and without annotation the framework would refuse to do it's job.
What is more @Nullable
might be used with @NotNull
annotation. Here you can find some tips how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.
Different tools may interpret the meaning of @Nullable
differently. For example, the Checker Framework and FindBugs handle @Nullable
differently.
上一篇: 当使用@EJB时,每个托管bean都得到它自己的@EJB实例吗?
下一篇: @Nullable注释用法