Say I have a class with an invariant that a certain instance variable is never null. I also want to use jsr305 null annotations correctly. The class is exposed as an API, so I cannot rely on the annotations to prevent nulls; I also need to check for null at runtime.
public final class NonNullString {
private final String string;
public NonNullString(String string) {
if (string == null) throw new NullPointerException();
this.string = string;
}
public String getString() {
return string;
}
}
What is the best way to apply null annotations to this class? @javax.annotation.Nonnull
applied to the parameter of the constructor describes my intent, but then Eclipse's null analysis warns that the null check is dead code. I can suppress Eclipse's warnings, if necessary, but the warning made me wonder if there is a better way to use the annotations.
EDIT: I am asking how to handle the interface between client code that may not use null annotations and code that uses null annotations.