gpt4 book ai didi

java - 为什么 android studio 告诉我 enum.valueOf 总是正确的?

转载 作者:行者123 更新时间:2023-11-30 00:53:36 25 4
gpt4 key购买 nike

我有一个奇怪的问题。这是我的枚举:

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);
}
}
}

在我的课上我有一个如果:

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

为什么 android studio 告诉我 ErrorInByte.valueOf(n) 总是正确的?我对其进行了测试,对于 ErrorInByte.valueOf(326),它等于 null。

警告信息:

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)

有什么方法可以消除警告吗?我讨厌警告...

最佳答案

发生的事情是 Enums 已经有一个不可覆盖的 valueOf 方法。这意味着您实际上是在调用自己定义的 valueOf,但 IDE 假定它是静态 valueOf。因此,为了解决您的问题,您必须将您的方法重命名为类似

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

关于java - 为什么 android studio 告诉我 enum.valueOf 总是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com