Question

I have a class definition like below. I want it to be a singleton.

public class MyClass {
    public static MyClass sInstance;
    public static final int STATUS_CONSTANT = 0;
    public int myProperty = 0;

    public static MyClass get() {
        if (sInstance==null) {
            sInstance= new MyClass();
        }
        return sInstance;
    }
}

When using it, JetBrains IdeaJ warns me that the comparison always returns false...

MyClass myClass = MyClass.get();
if (myClass.myProperty == MyClass.STATUS_CONSTANT) {
    ...
}

...whereas, it doesn't say anthing if I make it this way:

if (MyClass.get().myProperty == MyClass.STATUS_CONSTANT)

I did not get why it's angry about the first method!? In either way, it should be referencing the same static field (sInstance).

Was it helpful?

Solution

I couldn't see any problem with your condition so I copied your code into a NetBeans project and I didn't get any alert like that so I decided to run your code:

MyClass myClass = MyClass.get();
if (myClass.myProperty == MyClass.STATUS_CONSTANT) {
    System.out.println("OK");
}

And it prints "OK" so there is a case where the condition is not false.

I can see there are some reported bug in the "always false condition" IntelliJ checker:

http://youtrack.jetbrains.com/issue/IDEA-91390

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top