Where to put @Nullable on methods with nullable return types? [duplicate]

懵懂的女人 提交于 2019-12-01 04:23:22

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.

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 Framework are type annotations.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!