Let's say I have two classes. Each class has one parameter. Parameter of first class bounded to a second class and vice versa. But there is an additional requirement. This parameter must also be parametrized by class itself. This is better to be explained by example:
public class Class1<T extends Class2<Class1>> {
...
}
public class Class2<T extends Class1<Class2>> {
...
}
However, this construction doesn't work. Compiler tells Type parameter Class2 is not within its bound
. This is perfectly understandable, because compiler unable to resolve this endless recursion.
But I'd like to know is there any开发者_Go百科 elegant way to get what want by means of generic?
It looks like I suddenly found the answer.
public class Class1<T extends Class2<P, T>, P extends Class1<T,P>> {
}
public class Class2<T extends Class1<P, T>, P extends Class2<T, P>> {
}
It's completely mindblowing, but it seems to be working.
I think you should write like this:
class Class1<T extends Class2<? extends Class1<T>>> { }
class Class2<T extends Class1<? extends Class2<T>>> { }
or
class Class1<T extends Class2<? extends Class1<?>>> { }
class Class2<T extends Class1<? extends Class2<?>>> { }
It works on Java 1.6.
I am not sure I understand your question - note that since both classes in your example are generic, they as parameters should also include their generic parameters, which results in an endless recursion.
Circular generic references are possible, though in a slightly different way. Here is an example from an earlier answer of mine.
精彩评论