How to annotate a NonNull array?

I am using org.eclipse.jdt.annotation.NonNull to add additional information for static null analysis. I don't know how to annotate arrays correctly:

  • How can I say that an array reference is not null?
  • How can I say that an array consists of non-zero elements?

I tested:

    public static void test(@NonNull String[] a) {
        assert a != null;
    }

    public static void main(String[] args) {
        test(null);
    }

However, Eclipse does not mark it test(null);as erroneous.

+4
source share
2 answers

If you are using Java 8, it looks like this:

@NonNull Object [] o1;

o1    = null;           // OK
o1    = new Object[1];
o1[0] = null;           // NOT OK

Object @NonNull[] o2;

o2    = null;           // NOT OK
o2    = new Object[1];
o2[0] = null;           // OK
+7
source
  • How can I say that an array reference is not null?

You should put @NonNullafter the type declaration (but before the array brackets), for example,

public static void test(String @NonNull[] a) {
    assert a != null;
}
  1. How can I say that an array consists of non-zero elements?

There is in your original question.

EDIT: Java 8 ( ).

+4

All Articles