如何获得“通知”泛型在Java中工作? [英] How to get "circular" generics working in Java?
问题描述
我在编译涉及一些泛型的以下代码时遇到错误:
public abstract class State< T extends HasAState< ;?扩展状态< T>>> {
protected T parent;
public void setParent(){//为了这个问题,它被简化了!
parent.removeState(this); //错误在这里!
this.parent = parent;
parent.addState(this); //错误在这里!
}
}
public interface HasAState< T extends State< ;?扩展HasAState< T>>> {
public void addState(T state);
public void removeState(T state);
}
错误是:方法removeState(capture# 1-of?extends State< T>)的类型HasAState<捕获#1的?延伸状态< T>>不适用于参数(State< T>)
其实我想要的是类似于: class A implements HasAState
和 class B extends State< A>
其中 B
引用 A
并且可以调用 A.addState(B)
(仅因为 B
扩展
状态< A>
),其中 A
可以调用 B。 setParent(this)
。
如何声明我的类以便我打算做的工作?
谢谢
我同意Eran Zimmerman的评论。它接缝,你需要重新考虑你想要什么。
无论如何,我希望我已经理解这个问题,所以我改变了参数从一到两个,来描述 state
和 hasAState
分开。
public abstract class State< S extends State< S,H>,H extends HasAState< S,H>> {
protected H parent;
public void setParent(){
parent.removeState(this);
this.parent = parent; // !!!这条线没有任何效果!
parent.addState(this);
public interface HasAState< S extends State< S,H>,H extends HasAState< S,H>> {
public void addState(State< S,H> state);
public void removeState(State< S,H>状态);
}
此代码编译! - 注意 setParent
中第二行的警告。
I am having an error while compiling the following code involving a few generics:
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 errors are: 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>)
Actually what I would like to have is something like: class A implements HasAState
and class B extends State<A>
where B
has a reference to A
and can call A.addState(B)
(only because B
extends State<A>
) and where A
can call B.setParent(this)
.
How should I declare my classes so that what I intend to do work?
Thanks
I agree with the comment of Eran Zimmerman. It seams that you need to rethink about what you want.
Anyway I hope I have understand the problem right, so I changed the Parameter from one to tow, to describe the state
and the hasAState
separately.
public abstract class State<S extends State<S, H>, H extends HasAState<S, H>>{
protected H parent;
public void setParent(){
parent.removeState(this);
this.parent = parent; //!!!this line has no effect!!!
parent.addState(this);
}
}
public interface HasAState<S extends State<S, H>, H extends HasAState<S, H>> {
public void addState(State<S, H> state);
public void removeState(State<S, H> state);
}
This code compiles! -- be aware of the warning for the second line in setParent
.
这篇关于如何获得“通知”泛型在Java中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!