tags:

views:

58

answers:

3

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 elegant way to get what want by means of generic?

+3  A: 

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.

wax
+1  A: 

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.

Péter Török
Thanks for the answer. While the investigation I found that this endless recursion in parameter definition could be broken by second parameter, but according to the answer below there is even better solution.
wax
+2  A: 

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.

uthark
You still have the rightmost type name without its generic argument. Perhaps add a `<?>` if you want that sort of wildcardness.
Tom Hawtin - tackline
@tom hawtin Thank you, updated answer.
uthark