是否有隐式扩展到泛型类型的可为空注释?

Alf*_*Alf 6 java generics nullable

我\xe2\x80\x99m 在一个Java 项目中工作,并且我\xe2\x80\x99 最近开始向方法参数和返回值添加可为空的注释。我想知道是否可以将任何注释添加到参数中,以便它也涵盖泛型类型。目前我身边也有类似的案例:

\n\n
Map<String, String> someMethod(Map<String, Map<String, String>> arg) {\n...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

那就变成:

\n\n
@NotNull\nMap<@NotNull String, @NotNull String> someMethod(@NotNull Map<@NotNull String, @NotNull Map<@NotNull String, @NotNullString>> arg) {\n...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

显然,这变得难以阅读。我\xe2\x80\x99m对Java注释的内部不是很熟悉,所以也许这是\xe2\x80\x99不可能的?

\n

Ste*_*ann 3

可以通过合适的默认注释来减少空注释的数量。

以下内容适用于来自 的注释org.eclipse.jdt.annotation_2.x

特别@org.eclipse.jdt.annotation.NonNullByDefault是能够影响各种位置的类型,包括类型参数。

所以如果你写:

@NonNullByDefault
Map<String, String> someMethod(Map<String,Map<String,String>> arg) { ...
Run Code Online (Sandbox Code Playgroud)

这确实会被解释为

@NonNull Map<@NonNull String, @NonNull String> someMethod(@NonNull Map<@NonNull String, @NonNull Map<@NonNull String, @NonNull String>> arg) {
Run Code Online (Sandbox Code Playgroud)

它甚至有可能微调的效果@NonNullByDefault,并且它可以应用于单个方法,或整个类、包或模块。

如果签名仍然包含一些可为 null 的类型,则需要单独注释这些类型,以便@Nullable覆盖默认值,但这些异常应该比非 null 类型少得多。请注意, 和@NonNull@Nullable可以附加到所有相关位置的类型,同样包括类型参数。

有关 Eclipse 如何解释泛型感知空注释的一般文档可以在在线帮助中找到。