Annotation Interface Nullable


@Documented @Target(FIELD) @Retention(CLASS) public @interface Nullable
Indicates that the annotated field can be null.

The purpose of this annotation is to avoid using Optional on class fields and to provide a clear indication that the field can be null.

Using Optional on class fields is not recommended:

  • Java architecture intent: Optional has been initially introduced to provide a clear return type of methods that might not return a value
  • Memory Overhead: Optional is a wrapper, meaning that it stores both the Optional and the reference to the value are stored in memory
  • Serialization: Optional is not serializable
An example of the annotation us is presented below:

Non-compliant code

 
 private Optional<String> name;

 public Optional<String> getName() {
     return name;
 }

 public void setName(final String name) {
     this.name = Optional.ofNullable(name);
 }
 
 

Compliant code

 
 private @Nullable String name;

 public Optional<String> getName() {
     return Optional.ofNullable(name);
 }

 public void setName(final String name) {
     this.name = name;
 }
 
 
Since:
14.0
Author:
Bryan Cazabonne