Nullable

Hi,

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?

I can’t help with you question but I moved it to a more appropriate category where hopefully it will get the attention of someone who can.

1 Like
Subclass  localField1 = this.field1;
if (localField1 != null) {
    doSomething(localField1.abc)
}
    public void method1() {
        SubClass localField1 = field1;
        if (localField1 != null) {
            localField1.abc = 1;
        }
    }

This will eliminate the (extraordinarily rare) case where field1 could be set to null after the check for not equal to null.

2 Likes

Haha you beat me to it @J-N-K

Ah the local variable makes sense indeed when taking threading into account.

But I don’t understand how using this could solve that.
A thread could still change the value of localField1 after the if check has happened.

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.

1 Like

Sorry I should not read/response while I’m in a hurry.
The example with this. shows indeed the same as the other example, using a local variable.

Thanks