在具有可空返回类型的方法上放置@Nullable的位置? [英] Where to put @Nullable on methods with nullable return types?

查看:546
本文介绍了在具有可空返回类型的方法上放置@Nullable的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 javax.annotation.Nullable 将方法标记为可能返回 null value时,放在何处 @Nullable 注释?在方法上,还是返回类型?

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?

样式A:

@Nullable
public Object blah() { ... }

样式B:

public @Nullable Object blah() { ... }


推荐答案

这绝对是一个样式问题。

This is strictly a style issue.

无论你在源代码中的哪个位置编写注释,注释实际上是在方法上。那是因为 @Target javax.annotation.Nullable 定义的元注释,这使得 javax.annotation.Nullable 方法注释。您可以在任一位置编写注释,因为
Java语言规范语法允许方法注释穿插方法修饰符,例如 public

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.

我认为在返回类型之前放置注释更清楚。毕竟,它是非null的返回类型。说方法本身是非空的是没有意义的。

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.

在返回类型之前放置注释还有另一个重要的好处:你的代码与版本兼容 Nullable 的定义为类型注释。类型注释是在Java 8中引入的。它们比方法注释更具表现力,它们可以实现更强大的检查。例如,Eclipse支持的 Nullable 注释和 Checker Framework 是输入注释。

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.

这篇关于在具有可空返回类型的方法上放置@Nullable的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆