为什么使用 == 比较枚举会导致 PMD 警告?
Why does comparing enums using == cause a PMD warning?
下面使用 ==
比较两个枚举值:
MyEnum enum1 = blah(); // could return null
MyEnum enum2 = blahblah() // could return null
if (enum1 == enum2) {
// ...
}
但是 PMD 在第 3 行给出了 CompareObjectsWithEquals 警告:
Use equals() to compare object references
不确定我是否理解 source code for this check 但认为使用 ==
比较两个枚举是可以的,所以我想知道我的代码是否可以改进或检查不正确。
用.equals()
没问题,因为under the hoods,实例是和==
比较的。
public final boolean equals(Object other) {
return this==other;
}
请注意 .equals()
的实现是 final
,这意味着您不能在枚举中覆盖它。
这确实被接受为错误:
然而,捕捉所有可能的情况似乎很棘手(引用较新的错误):
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.
("Your example" 指的是工单作者,不是 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;
}
下面使用 ==
比较两个枚举值:
MyEnum enum1 = blah(); // could return null
MyEnum enum2 = blahblah() // could return null
if (enum1 == enum2) {
// ...
}
但是 PMD 在第 3 行给出了 CompareObjectsWithEquals 警告:
Use equals() to compare object references
不确定我是否理解 source code for this check 但认为使用 ==
比较两个枚举是可以的,所以我想知道我的代码是否可以改进或检查不正确。
用.equals()
没问题,因为under the hoods,实例是和==
比较的。
public final boolean equals(Object other) {
return this==other;
}
请注意 .equals()
的实现是 final
,这意味着您不能在枚举中覆盖它。
这确实被接受为错误:
然而,捕捉所有可能的情况似乎很棘手(引用较新的错误):
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.
("Your example" 指的是工单作者,不是 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;
}