繁体   English   中英

如何实现具有枚举的接口,其中接口扩展为Comparable?

[英]How to implement an interface with an enum, where the interface extends Comparable?

考虑以下代码:

public interface Foo extends Comparable<Foo> {}

public enum FooImpl implements Foo {}

由于类型擦除的限制,我收到以下错误:

java.lang.Comparable不能使用不同的参数继承: <Foo><FooImpl>

我有以下要求:

  • FooImpl需要是一个枚举,因为我需要将它用作注释中的默认值。
  • 我的界面合同是它需要具有可比性。

我已经尝试在接口中使用泛型边界,但Java不支持。

枚举已实现可比性,因此您无法覆盖它。

关于为什么 - 实现 - 实现 - 接口的一般答案。

枚举实现Comparable,因此FooImpl最终使用不兼容的参数扩展Comparable两次。

以下将有效:

public interface Foo<SelfType extends Foo<SelfType>> extends Comparable<SelfType> { ... }

public enum FooImpl implements Foo<FooImpl> { ... }

实际上你会得到的错误是:

接口Comparable不能使用不同的参数实现多次: Comparable<FooImpl>Comparable<Foo>

由于枚举FooImpl已经隐式实现了Comparable<FooImpl> ,因此无法再将其重写为Comparable<Foo>.

暂无
暂无

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

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