简体   繁体   中英

IntelliJ IDEA contract for not null return value

I use @contract Java annotation in IntelliJ IDEA 14.1.5 But in this case it seems not working:

private String name;

void setName(String name) {
    this.name = null;     // for test
}

@Contract("-> !null")
String getName() {
    return this.name;
}

Is it possible to resolve this problem?

Thank you for any reply!

The @Contract("-> !null") is on the method getName . That means when you call getName in a conditional comparison to null , IntelliJ will warn you the condition is always false and offer to simplify the code. In your example, there's no calls to getName , so there's no visible effect.

public class A {
    @Contract("-> !null")
    String getName() {
        return "jimmy";
    }

    void method() {
        if (getName() == null) { // for test
            System.out.println("null");
        }
    }
}

If you mean to have IntelliJ to warn you if null is attempted to be assigned to the variable name , use the @NotNull annotation on the field.

public class A {
    @NotNull private String name;

    public static void main(String[] args) {
        A a = new A();
        a.name = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM