我将再次重命名您的类,以便一切都更具可读性。那么,让我们:
public class First<T extends Second, U extends First<T, U>> {
Third<T, U> c;
void test() {
c.acceptParameterOfTypeA(this);
}
}
class Second {
}
public class Third<X extends Second, Y extends First<X, Y>> {
void acceptParameterOfTypeA(Y a) {
}
}
从定义来看c
成员 (Third<T, U>
),我们可以得出结论c
将公开具有此签名的方法:
void acceptParameterOfTypeA(U a) { .. }
What is U
? U
是一个子类型First<T, U>
.
But if U
可以替换为First
类型擦除后,这意味着First extends First<T, First>
,这不是真的,因为U
代表子类型First
,它是用一些具体的子类型参数化的Second
and First
.
为了到达U
,你可以应用所谓的Get This
方法。
首先,既然你需要U
,这是一个子类型First
,但无法从中获取First
,你可以引入一个abstract
返回它的方法:
abstract class First<T extends Second, U extends First<T, U>> {
Third<T, U> c;
void test() {
c.acceptParameterOfTypeA(getU());
}
abstract U getU();
}
然后,实现一个示例子类First
,称为Fourth
,这延伸了First
一些具体类型T
and U
, 例如:
class Fourth extends First<Second, Fourth> {
Fourth getU() {
return this;
}
}
In the getU()
方法,只需要做return this;
因为这将返回正确的替代品U
在超类中。
更多信息:
- “getThis”技巧是什么? http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206
- 具有泛型的策略模式 http://www.javaspecialists.co.za/archive/newsletter.do?issue=123