I’m working on a new binding and am running into some warnings with the @NonNullByDefault and @Nullable annotation.
@NonNullByDefault
public class Example {
static class SubClass {
public int abc;
}
@Nullable
private SubClass field1;
public void method1() {
if (field1 != null) {
field1.abc = 1;
}
}
}
The field1.abc = 1; statement gives this warning:
Potential null pointer access: this expression has a ‘@Nullable’ type
I don’t understand how I can fix that warning.
Does anyone have an idea on what I can do to fix this?
The class member just holds reference to an object. If you set it to null you can‘t access the object anymore are it will be removed by the garbage collector later. If you make a copy of the reference to a local variable, you can still access the object, because only the reference in the class member is removed, not the object itself. After your method exists, your local copy will also be garbage collected, the object than again has no reference and will be removed.