Cyclic generic dependenices

こ雲淡風輕ζ 提交于 2020-01-24 19:35:26

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3147308/cyclic-generic-dependenices

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!