通用接口实现方法
这可能是代码的气味,但我想知道在Java中是否可以做到这一点。鉴于我有界面:
public interface State {
String getStateName();
}
而且我有一个这样的实现:
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);
}
}
另一种是这样:
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; }
}
当我执行以下操作时,它失败了,因为我无法在枚举中实现equals
的实现:
assertTrue(Arrays.asList(new DefaultState("STATE1")).contains(EnumState.STATE_1)); // fails
有没有办法做这项工作还是最终的答案您不应该混合这样的实现?
This is possibly a code smell but I was wondering if this might be possible in Java. Given that I have my interface:
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
行
arrays.aslist(new defaultState(“ state1”))。包含(enumstate.state_1)
use cance contains contains contains,该方法的实现使用了参数的等效方法(此处枚举)比较,因此它将返回false,因为它将比较是否是相同的枚举实例。您不能覆盖枚举,因此可能的解决方案是流式传输并找到使用DefaultState类中的Equals overriden匹配条件的任何元素:
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.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 :