[英]How to implement an interface with an enum, where the interface extends Comparable?
Consider this code: 考虑以下代码:
public interface Foo extends Comparable<Foo> {}
public enum FooImpl implements Foo {}
Due to the restrictions of type erasure, I receive the following error: 由于类型擦除的限制,我收到以下错误:
java.lang.Comparable cannot be inherited with different arguments:
<Foo>
and<FooImpl>
java.lang.Comparable不能使用不同的参数继承:<Foo>
和<FooImpl>
I have the following requirements: 我有以下要求:
FooImpl
needs to be an enum, because I need to use it as a default value in annotations. FooImpl
需要是一个枚举,因为我需要将它用作注释中的默认值。 I already tried using generic bounds in the interface, but this is not supported in Java. 我已经尝试在接口中使用泛型边界,但Java不支持。
Enum already implements comparable so you can't override it. 枚举已实现可比性,因此您无法覆盖它。
A general answer regarding why-would-an-enum-implement-an-interface . 关于为什么 - 实现 - 实现 - 接口的一般答案。
Enums implement Comparable, so FooImpl ends up extending Comparable twice with incompatible arguments. 枚举实现Comparable,因此FooImpl最终使用不兼容的参数扩展Comparable两次。
The following will work: 以下将有效:
public interface Foo<SelfType extends Foo<SelfType>> extends Comparable<SelfType> { ... }
public enum FooImpl implements Foo<FooImpl> { ... }
Actually the error you will get is : 实际上你会得到的错误是:
The interface Comparable cannot be implemented more than once with different arguments :
Comparable<FooImpl>
andComparable<Foo>
接口Comparable不能使用不同的参数实现多次:Comparable<FooImpl>
和Comparable<Foo>
As enum FooImpl
already implementing Comparable<FooImpl>
implicitly, you can not override it again as Comparable<Foo>.
由于枚举FooImpl
已经隐式实现了Comparable<FooImpl>
,因此无法再将其重写为Comparable<Foo>.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.