Are there any nullable annotations that implicitly extend to generic types?

Alf :

I’m working in a Java project and I’ve started recently to add nullable annotations to method arguments and return values. I was wondering if there are any annotations that can be added to an argument so that it covers generic types as well. Right now I have cases similar to:

Map<String, String> someMethod(Map<String, Map<String, String>> arg) {
...
}

That become:

@NotNull
Map<@NotNull String, @NotNull String> someMethod(@NotNull Map<@NotNull String, @NotNull Map<@NotNull String, @NotNullString>> arg) {
...
}

Which becomes, obviously, hard to read. I’m not very familiar with the internals of Java annotations, so maybe this isn’t possible?

Stephan Herrmann :

Reducing the number of null annotations can be achieved with a suitable default annotation.

The following applies to annotations from org.eclipse.jdt.annotation_2.x:

In particular @org.eclipse.jdt.annotation.NonNullByDefault is able to influence types in various positions, including type arguments.

So if you write:

@NonNullByDefault
Map<String, String> someMethod(Map<String,Map<String,String>> arg) { ...

this will indeed be interpreted as

@NonNull Map<@NonNull String, @NonNull String> someMethod(@NonNull Map<@NonNull String, @NonNull Map<@NonNull String, @NonNull String>> arg) {

It is even possibly to fine-tune the effect of @NonNullByDefault, and it can be applied to individual methods, or entire classes, packages or modules.

If a signature still contains a few nullable types, those need to be annotated individually as @Nullable in order to override the default, but those exceptions should be much fewer than the nonnull types. Note, that both @NonNull and @Nullable can be attached to types in all relevant positions, again including type arguments.

General documentation on how Eclipse interprets generics-aware null annotations can be found in the online help.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105571&siteId=1