2016-11-11 10 views
1

Ich habe eine seltsame Frage. Das ist mein Enum:Warum Android Studio sagt mir, dass enum.valueOf ist immer wahr?

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 meiner Klasse habe ich ein, wenn:

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

Warum Android Studio sagt mir, dass ErrorInByte.valueOf (n) ist immer wahr? Ich habe es getestet und für ErrorInByte.valueOf(326) ist es gleich null.

Warnmeldung:

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) 

Gibt es eine Möglichkeit, die Warnung zu entfernen? Ich hasse Warnungen ...

+0

umbenennen Weil Sie nicht ein Element in der Karte mit dem Wert 326. –

+0

sicher Wert vorliegen Stellen haben oder nicht –

+2

Ihre Frage und Ihre Erklärung ergibt keinen Sinn. Zuerst sagst du, es ist immer Null, dann sagst du, es ist immer wahr ... –

Antwort

1

Was passiert ist, dass Enums bereits eine nicht übersteuern können valueOf Methode. Das bedeutet, dass Sie tatsächlich Ihre eigene definierte valueOf aufrufen, aber die IDE geht davon aus, dass es sich um die statische valueOf handelt. Also, um das Problem zu beheben, müssen Sie Ihre Methode, um so etwas wie

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

Daran habe ich nicht gedacht. Habe den Namen geändert und es ist jetzt ok ... Danke – Georgi

Verwandte Themen