在 Java 的枚举中使用等于字符串

Using equals with string in enum in Java

假设我们有下一个枚举,我想向它添加 equals(String) 方法,因为使用相同代码的其他人通常会在使用 equals 方法比较枚举和字符串时出错。

public enum SomeEnum {
    CONSTANT1("DATABASE_CONSTANT1"),
    CONSTANT2("DATABASE_CONSTANT2");

    private final String databaseConstant;

    SomeEnum(String databaseConstant) {

        this.databaseConstant = databaseConstant;
    }

    public String getDatabaseConstant() {
        return databaseConstant;
    }

    public boolean equals(String databaseConstant) {
        return getDatabaseConstant().equals(databaseConstant);
    }
}

问题:使用这种方法有什么陷阱吗?

某些绑定到 equals(..) 的合同将被违反。 特别是对称性。这可能会导致未来出现各种问题。

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

建议不支持误用equals(..)'other people'

要尽早找到使用 equals(String) 的代码,您可以这样做:

@Deprecated
public boolean equals(String databaseConstant) {
  throw new IllegalArgumentException("Never use equals(String) for SomeEnumtype "); 
}

@Deprecated 大多数 IDE 将任何呼叫标记为警告。


更新
正如 在他的评论和回答中所写,如果您使用例如sonar sonar 的警告足以解决您的问题,而无需添加我在上面提供的解决方案'dead code'。

添加此方法以避免错误使用标准方法,因为不建议 equals()
此外,即使您在 SomeEnum class 中添加了此方法,您也不能也不想在 String class![=26= 中执行相同的操作] 所以 "DATABASE_CONSTANT1".equals(SomeEnum.DATABASE_CONSTANT1) 仍然是可能的,不会 return 你想要什么。

我认为 Lint 和 Sonar 等代码分析工具可以更好地处理不良做法。

例如,Sonar 定义了 Silly equality checks should not be made 错误规则。
这会对您需要的 equals() 用法进行多次检查:

comparing unrelated classes

这里有更多详细信息:

Comparisons of dissimilar types will always return false. The comparison and all its dependent code can simply be removed. This includes:

comparing an object with null

comparing an object with an unrelated primitive (E.G. a string with an int)

comparing unrelated classes

comparing an unrelated class and interface

comparing unrelated interface types

comparing an array to a non-array

comparing two arrays