【发布时间】:2011-11-03 10:42:35
【问题描述】:
我在编译以下涉及一些泛型的代码时出错:
public abstract class State<T extends HasAState<? extends State<T>>>{
protected T parent;
public void setParent(){ // It's been simplified for the sake of the question!
parent.removeState(this); // Error here!
this.parent = parent;
parent.addState(this); // Error here!
}
}
public interface HasAState<T extends State<? extends HasAState<T>>> {
public void addState(T state);
public void removeState(T state);
}
错误是:The method removeState(capture#1-of ? extends State<T>) in the type HasAState<capture#1-of ? extends State<T>> is not applicable for the arguments (State<T>)
实际上我想要的是:class A implements HasAState 和 class B extends State<A> 其中B 引用了A 并且可以调用A.addState(B)(只是因为B 扩展了State<A>)和其中A 可以调用B.setParent(this)。
我应该如何声明我的类以便我打算做的工作?
谢谢
【问题讨论】:
-
我认为你应该重新考虑你的设计......所有这些泛型真的有必要吗?也许有一种更简单的方法来实现您想要实现的目标?
-
Here 是在 Java 中创建循环泛型引用的一种方法。如果这不是您想要的,browse similar threads.
-
我尝试了您的建议,但在同一位置出现另一个错误:
The method addState(E) in the type HasAState<P,E> is not applicable for the arguments (State<P,E>)
标签: java generics compiler-errors