13

I'm using org.eclipse.jdt.annotation.NonNull to add extra information for static null analysis. I donn't know how to annotate arrays correctly:

  1. How can I say that an array reference is non-null?
  2. How can I say that an array consists of non-null elements?

I've tested:

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

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

However, Eclipse doesn't mark test(null); as wrong.

Nathan
  • 8,093
  • 8
  • 50
  • 76
Vertex
  • 2,682
  • 3
  • 29
  • 43

2 Answers2

15

If you 're using Java 8, it looks as follows:

@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
Nathan
  • 8,093
  • 8
  • 50
  • 76
René Winkler
  • 6,508
  • 7
  • 42
  • 69
5
  1. How can I say that an array reference is non-null?

You should've put @NonNull after the type declaration (but before the array brackets), eg.,

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

Your original question has that.

EDIT: For Java 8 compatibility, the syntax had to be changed a little (modified above code accordingly).

KrishPrabakar
  • 2,824
  • 2
  • 31
  • 44