简体   繁体   English

接口实现的通用 equals 方法

[英]Common equals method for interface implementations

This is possibly a code smell but I was wondering if this might be possible in Java. Given that I have my interface:这可能是一种代码味道,但我想知道这在 Java 中是否可行。鉴于我有我的界面:

public interface State {
    String getStateName();
}

and I have one implementation like this:我有一个这样的实现:

public class DefaultState implements State {
    final String stateName;

    public DefaultState(String stateName) {
        this.stateName = stateName;
    }

    @Override
    public String getStateName() {return stateName; }

    @Override
    public boolean equals(Object other) {
        return ((State)other).getStateName().equals(this.stateName);
    }
}

and another like this:另一个是这样的:

public enum EnumState implements State {
    STATE_1("STATE1"),STATE_2("STATE_2");

    final String stateName;
    
    EnumState (String stateName) {
        this.stateName = stateName;
    }

    @Override
    public String getStateName() {return stateName; }
}

When I do the following it fails because I cant override how equals is implemented in the enumeration:当我执行以下操作时,它失败了,因为我无法覆盖枚举中equals的实现方式:

assertTrue(Arrays.asList(new DefaultState("STATE1")).contains(EnumState.STATE_1)); // fails

Is there a way of making this work or is the ultimate answer you shouldn't be mixing implementations like that?有没有一种方法可以使这项工作起作用,或者最终的答案是您不应该混合这样的实现吗?

The line Arrays.asList(new DefaultState("STATE1")).contains(EnumState.STATE_1) use contains method, the implementation of this method use the equals method of the parameter (Enum here) for the comparaison, so it will return false because it will compare if this is the same Enum instance or not. Arrays.asList(new DefaultState("STATE1")).contains(EnumState.STATE_1)这一行使用了contains方法,该方法的实现使用参数(此处为Enum)的equals方法进行比较,所以会返回false因为它会比较这是否是同一个 Enum 实例。

You cannot override equals on Enums, so a possible solution is to stream and find any element that match your condition using the equals overriden in the DefaultState class:您不能覆盖 Enums 上的 equals,因此一个可能的解决方案是 stream 并使用 DefaultState class 中覆盖的 equals 找到符合您条件的任何元素:

assertTrue(Arrays.asList(new DefaultState("STATE1"))
                              .stream()
                                    .anyMatch(state -> state.equals(EnumState.STATE_1)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM