java 将@Nullable 放在具有可为空返回类型的方法上的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25958995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where to put @Nullable on methods with nullable return types?
提问by kevinarpe
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?
当javax.annotation.Nullable
用于将方法标记为“可能返回null
值”时,@Nullable
注解放在哪里?关于方法,还是返回类型?
Is there any technical difference, or is this strictly a style issue?
是否有任何技术差异,或者这严格来说是一个风格问题?
Style A:
风格A:
@Nullable
public Object blah() { ... }
Style B:
风格B:
public @Nullable Object blah() { ... }
回答by mernst
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
.
不管你在源代码的哪个地方写注解,注解其实都在方法上。那是因为@Target
的定义上的元注释javax.annotation.Nullable
,它构成javax.annotation.Nullable
了一个方法注释。您可以在任一位置编写注释,因为 Java 语言规范语法允许方法注释与方法修饰符如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 Frameworkare type annotations.
将注释放在返回类型之前还有另一个重要好处:您的代码与Nullable
定义为类型注释的版本兼容。Java 8 中引入了类型注解。它们比方法注解更具表现力,并且能够实现更强大的检查。比如Nullable
Eclipse和Checker Framework支持的注解就是类型注解。
回答by mkazma
Option type will do the trick for you. A return type of Option indicates that the method may return an Object, or it may return a special value of type None or null.
选项类型将为您解决问题。Option 的返回类型表示该方法可能返回一个 Object,或者它可能返回一个 None 或 null 类型的特殊值。