Georgi Georgi - 28 days ago 7
Java Question

Why android studio is telling me that enum.valueOf is always true?

I have a little strange question. This is my enum:

enum ErrorInByte{
ERROR_BIT0(3),
ERROR_BIT2(4),
ERROR_BIT3(5),
ERROR_BIT4(7),
ERROR_BIT5(13),
ERROR_BIT7(15),

private int value;
ErrorInByte(int value) {
this.value = value;
}

public static ErrorInByte valueOf(int value){
return intToErrorInByte.get(value);
}

private static final Map<Integer, ErrorInByte> intToErrorInByte= new HashMap<>();
static {
for (ErrorInByte type : ErrorInByte.values()) {
intToErrorInByte.put(type.value, type);
}
}
}


In my class I have an if:

int n;
//Code that changes n to a value
if(n > 0 && ErrorInByte.valueOf(n) != null){
//do stuff...
}


Why android studio tells me that ErrorInByte.valueOf(n) is always true? I tested it and for
ErrorInByte.valueOf(326)
it equals null.

Warning message :

This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.


Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException errors.

More complex contracts can be defined using @Contract annotation, for example:

@Contract("_, null -> null") — method returns null if its second argument is null
@Contract("_, null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise
@Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it

The inspection can be configured to use custom @Nullable
@NotNull annotations (by default the ones from annotations.jar will be used)


Is there any way to remove the warning? I hate warnings...

Answer

What happen is that Enums already have a non override able valueOf method. This means that you are in fact calling your own defined valueOf, but the IDE assumes that it's the static valueOf. So in order to fix your issue you have to rename your method to something like

 public static ErrorInByte lookUpByCode(int value){
        return intToErrorInByte.get(value);
    }