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

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

问题描述

当使用javax.annotation.Nullable 将方法标记为可能返回null 值"时,@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.

无论你在源代码的哪个地方写注解,注解其实都在方法上.这是因为 javax.annotation.Nullable 定义上的 @Target 元注解,使得 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.

我认为将注释放在返回类型之前更清晰.毕竟,它是非空的返回类型.说一个方法本身是非空是没有意义的.

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天全站免登陆