Search code examples
javanull-test

How to properly write a null test on input that is nullable to avoid warnings in Java?


How to write a proper test on a method that can return a null to assign the value to a nonnull variable?

@Nonnull String abc;
if(holderForState.getNodeElementSelectedAPI() == null || holderForState.getNodeElementSelectedAPI().equals("")) {
    throw new IllegalArgumentException("SelectedAPI is empty or null during logic usage");
}
abc = holderForState.getNodeElementSelectedAPI();

Why does VS-code tell me that: Null type safety: The expression of type 'String' needs unchecked conversion to conform to '@Nonnull String'Java(16778128) on abc assignment line? I am literally testing if it is null 1 line above and throwing out of context if it is...

I tried multiple versions of this test, but I get the same. To make it simpler I am showing the assignment, whereas in reality I am using abc as a method parameter, with same outcomes.


Solution

  • You are always calling the .getNodeElementSelectedAPI(); method. It might be the case that the return type of this methods is different after the second call so it can possible get null.

    I would recommend you to write your code something like

    String abc = holderForState.getNodeElementSelectedAPI();
    if( abc == null || abc.equals("")) {
        throw new IllegalArgumentException("SelectedAPI is empty or null during logic usage");
    }
    

    The variable abc can get null but it would still trigger the IllegalArgumentException.