Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullability of an array in Eclipse

Tags:

java

suggest the following code in Eclipse 4.30:

    public void doSomething(@NonNull SomeType[] pArray) {
       // Whatever
    }

If I enable checks for nullability (Preferences/Java Compiler/"Errors/Warnings"/Null analysis/Enable annotation based null-analysis), then I notice the following:

The Compiler takes the parameter type as "an array of SomeType elements, all of which are non-null", or in other words an array of @NonNull SomeType. (If you don't believe me, change SomeType to byte, and notice the error message, because byte is a primitive type, so @NonNull byte makes no sense.)

Which is all very well. However, I would like to tell the compiler, that the array itself is non-null. Is there any possibility to express this? (Let's say @NonNull (SomeType[]) pArray.)

Thanks!

like image 815
user1774051 Avatar asked Aug 05 '26 19:08

user1774051


1 Answers

Sure, of course. There are 2 layers of nullity to this story. In fact, with, say, an Object[][], there are 3 different nullity.

It could be a nullable reference to an array, which contains definitely-not-null arrays of definitely-not-null objects.

It could be a definitely-not-null reference to an array, which contains nullable refs to arrays of definitely-not-null objects.

And so on.

The syntax to specify at each level is like this:

@Nullable String @NonNull [] x

That means: a definitely-not-null reference to an array of nullable strings.

Each [] can be prefixed with annotations, applying to that 'layer'.

The same '3 layers' situation applies to a list of a list of objects, but the syntax is a lot more obvious there:

@NonNull List<@Nullable String>

Is the equivalent.

BIG CAVEAT: This requires the annotation to marked as applying to TYPE_USE. Many nullity annotations were created in the java 1.5 days which did not have TYPE_USE; only PARAMETER and METHOD and FIELD. Many nullity annotations, as a consequence, still only target P/M/F instead of T_U. For these, what you want simply isn't possible. Update to a better nullity annotation system, or embrace how they work.

Some major annotation libraries that work on the basis of TYPE_USE:

Library Annotation class
Eclipse Java development tools (JDT) org.eclipse.jdt.annotation.NonNull
Checker Framework org.checkerframework.checker.nullness.qual.NonNull and PolyNull
JSpecify org.jspecify.annotations.Nullable
like image 78
rzwitserloot Avatar answered Aug 07 '26 10:08

rzwitserloot