java - 为什么使用 == 比较枚举会导致 PMD 警告?

标签 java enums comparison pmd

以下使用 == 比较两个枚举值:

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/

相关文章:

java - 如何使 Java 中的 XPathFactory newInstance 失败?

java - 如何在枚举中定义通用成员变量?

java - 如何处理基于枚举的开关中的默认情况?

.net - 如何将枚举值序列化为 int?

c++ - 如何比较等效类型的元组而不考虑类型顺序?

java - 前置字符集

java - 如何在 Context.MODE_PRIVATE 中创建嵌套文件夹和文件?

java - spring-security 错误登录的用户

Python - 默认情况下,用户定义的类具有 __cmp__() 和 __hash__() 方法?或者?

javascript - 如何获取最接近值的数组项的索引?