相关代码如下:
public interface Artifact {}
public interface Bundle implements Artifact {}
public interface Component implements Artifact {}
public interface State<T extends Artifact> {
void transition(T artifact, State<T> nextState);
}
这允许我定义这个枚举:
enum BundleState implements State<Bundle> {
A, B, C;
public void transition(Bundle bundle, State<Bundle> nextState) {}
}
}
但是我想要的方法签名是:
public void transition(Bundle bundle, BundleState nextState) {}
}
但这不编译。显然问题在于我如何在 State
界面中定义 T
,但我不知道如何修复它。
谢谢, 唐
最佳答案
事情可能开始变得笨拙,但您可以将 State
更改为:
public interface State<T extends Artifact, U extends State<T, U>> {
void transition(T artifact, U nextState);
}
并将 BundleState 更改为:
public enum BundleState implements State<Bundle, BundleState> {
A, B, C;
public void transition(Bundle bundle, BundleState nextState) {}
}
关于Java 泛型难题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3915538/