以下使用 ==
比较两个枚举值:
MyEnum enum1 = blah(); // could return null
MyEnum enum2 = blahblah() // could return null
if (enum1 == enum2) {
// ...
}
但是 PMD 给出了一个 CompareObjectsWithEquals第 3 行警告:
Use equals() to compare object references
不确定我是否理解 source code for this check但认为使用 ==
比较两个枚举是可以的,所以我想知道我的代码是否可以改进或者检查不正确。
最佳答案
这确实被接受为错误:
但是,捕获所有可能的情况似乎很棘手(引用较新的错误):
That one is a bit tricky, as in order to determine, whether a type is a Enum, we need type resolution.
I was able to adjust the rule to check, whether the type of the variables is an Enum. This works only, if the Enum types are on the "auxclasspath" of pmd, so that the type resolution can find it.
Your example in isolation would still trigger this false positive, as PMD doesn't know what ProcessingStatus is. I verified it with java.math.RoundingMode, which is always on the classpath and will be resolved.
(“您的示例”指的是票证作者,而不是 Stack Overflow 上的 OP)
您的案例可能适用于 PMD 5,您链接的源属于 PMD 4。
更新:current source包含对枚举的额外检查:
// skip, if it is an enum
if (type0.getType() != null && type0.getType().equals(type1.getType()) && type0.getType().isEnum()) {
return data;
}
关于java - 为什么使用 == 比较枚举会导致 PMD 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30916139/