[英]Java generics type argument Project is not within bounds of type-variable E
[英]How to fix "type argument S is not within bounds of type-variable E" in Java
我正在尝试通过使用接口定义一些基本访问方法来对不同的 Enum 类进行多态访问。 例如:
package com.company;
public interface StatesInterface<E extends Enum<E>> {
E getOneState();
E getTwoState();
E getThreeState();
}
还有一些实现:
package com.company;
public enum States implements StatesInterface<States> {
ONE, TWO, THREE, FOUR;
@Override
public States getOneState() {
return ONE;
}
@Override
public States getTwoState() {
return TWO;
}
@Override
public States getThreeState() {
return THREE;
}
}
注意:我知道这段代码有问题,因为接口通过非静态接口提供静态枚举值,但我不知道如何解决它。
当我尝试将此接口用作类中的类型约束时,我遇到了类型错误。 例如:
package com.company;
public class Lifecycle<S extends StatesInterface> {
private S state;
public void transit() {
state = state.getOneState(); // <---- incompatible types
}
}
在这种情况下,我不能分配state.getOneState();
Enum
类型到StatesInterface<Enum>
类型的state
。
当我尝试将泛型类型更改为Lifecycle<S extends StatesInterface<S>>
compiles 时说我Error:(3, 50) java: type argument S is not within bounds of type-variable E
。
我的目标是使用通用接口创建一组不同的 Enum 类,以创建一个将类Lifecycle
泛化为特定 Enum 类型的新类。
是否可以使用提供的代码来实现这一点以及如何修复它?
我想你要找的是这个:
class Lifecycle<S extends Enum<S> & StatesInterface<S>>
相比之下,你的定义是这样的:
interface StatesInterface<E extends Enum<E>>
enum States implements StatesInterface<States>
class Lifecycle<S extends StatesInterface>
然后getOneState()
只返回一个类型Object extends Enum<Object>
,因为您通过不给它类型参数来使用StatesInterface
的原始类型,这与类型S extends StatesInterface
不兼容,从而为您提供"Type mismatch: cannot convert from Enum to S"
通过将您的定义更改为class Lifecycle<S extends Enum<S> & StatesInterface<S>>
您允许getOneState()
返回S extends Enum<S> & StatesInterface<S>
这当然兼容设置为变量类型S
, S state = getOneState()
从这里拿走什么
您应该努力避免使用原始类型,因为它们放弃了泛型的类型安全性,并且通常也不会与其他泛型很好地配合,正如您在此处所经历的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.