本文翻译自:@Nullable annotation usage
I saw some method in java declared as: 我在Java中看到一些方法声明为:
void foo(@Nullable Object obj)
{ ... }
What's the meaning of @Nullable
here? @Nullable
在这里是什么意思? Does it mean the input could be null
? 这是否意味着输入可能为null
?
Without the annotation, the input can still be null, so I guess that's not just it? 如果没有注释,输入仍然可以为null,所以我猜不仅仅是吗?
#1楼
参考:https://stackoom.com/question/x3t2/Nullable注释用法
#2楼
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 . 它也为诸如FindBugs之类的代码分析器提供了提示。 For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning. 例如,如果这样的方法取消引用其参数而不先检查null,则FindBugs将发出警告。
#3楼
This annotation is commonly used to eliminate NullPointerExceptions
. 此批注通常用于消除NullPointerExceptions
。 @Nullable
is often says that this parameter might be null
. @Nullable
通常说这个参数可能为null
。 Good example of such behaviour can be found in Google Guice . 可以在Google Guice中找到这种行为的一个很好的例子。 In this lightweight dependency injection framework you tell that this dependency might be null
. 在这个轻量级的依赖项注入框架中,您可以说此依赖项可能为null
。 If you would try to pass null
and without annotation the framework would refuse to do it's job. 如果您尝试传递null
且没有注释,则该框架将拒绝执行此工作。
What is more @Nullable
might be used with @NotNull
annotation. 还有更多@Nullable
可以与@NotNull
注释一起使用。 Here you can find some tips how to use them properly. 在这里,您可以找到一些如何正确使用它们的提示。 Code inspection in IntelliJ checks the annotations and helps to debug the code. IntelliJ中的代码检查可检查注释并帮助调试代码。
#4楼
Different tools may interpret the meaning of @Nullable
differently. 不同的工具可能会以不同的方式解释@Nullable
的含义。 For example, the Checker Framework and FindBugs handle @Nullable
differently . 例如, Checker Framework和FindBugs @Nullable
不同的方式处理@Nullable
。