Eclipse has null pointer annotation analysis and you can attach external annotations. http://www.lastnpe.org/ has documentation on that in case you stumble here and are confused.
Anyway if I attach the JDK external annotations (also known as *.eea files) and turn on the annotation analysis I can do the following (assume someObject is @Nullable
):
Objects.requireNonNull(someObject);
someObject.toString() // No error/warning here as Eclipse apparently figured out that someObject isn't null.
The eea definition of requireNonNull
is:
requireNonNull
<T:Ljava/lang/Object;>(TT;)TT;
<T:Ljava/lang/Object;>(T0T;)T1T;
Now if I make my own library lets call it MyObjects and attach the source and annotation (exactly like Objects.requireNonNull) I get a warning when I do the above:
MyObjects.likeRequireNonNull(someObject);
someObject.toString() // NP analysis warning/error here
Obviously I can get around it by re-assigning:
someObject = MyObjects.likeRequireNonNull(someObject);
someObject.toString(); // No error or warning.
but in some cases that isn't desirable (lambdas).
The above makes since because someObject is now being reassigned to a @NonNull
.
What doesn't make since is how I can replicate the behavior of Objects.requireNonNull
where I don't need to assign it back. I can't figure out how Eclipse knows via the external annotations that Objects.requireNonNull
will guarantee the input variable not to be null in later usage.
EDIT: Apparently Objects.requireNonNull might be on a special whitelist according to this bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=553272