Annotation Interface RequiresNonNull


Indicates a method precondition: the method expects the specified expressions to be non-null when the annotated method is invoked.

For example:

 import org.checkerframework.checker.nullness.qual.RequiresNonNull;
 import org.checkerframework.checker.nullness.qual.NonNull;
 import org.checkerframework.checker.nullness.qual.Nullable;

 class MyClass {
   @Nullable Object field1;
   @Nullable Object field2;

   @RequiresNonNull({"field1", "#1.field1"})
   void method1(@NonNull MyClass other) {
     field1.toString();           // OK, this.field1 is known to be non-null
     field2.toString();           // error, might throw NullPointerException
     other.field1.toString();     // OK, other.field1 is known to be non-null
     other.field2.toString();     // error, might throw NullPointerException
   }

   void method2() {
     MyClass other = new MyClass();

     field1 = new Object();
     other.field1 = new Object();
     method1(other);                   // OK, satisfies method precondition

     field1 = null;
     other.field1 = new Object();
     method1(other);                   // error, does not satisfy this.field1 method precondition

     field1 = new Object();
     other.field1 = null;
     method1(other);                   // error, does not satisfy other.field1 method precondition
   }
 }
 
Do not use this annotation for formal parameters (instead, give them a @NonNull type, which is the default and need not be written). The @RequiresNonNull annotation is intended for other expressions, such as field accesses or method calls.
See the Checker Framework Manual:
Nullness Checker
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static @interface 
    A wrapper annotation that makes the RequiresNonNull annotation repeatable.
  • Required Element Summary

    Required Elements
    Modifier and Type
    Required Element
    Description
    The Java expressions that need to be NonNull.