![](/img/trans.png)
[英]How do I return a generic type while having another generic type as parameter, both required to implement an interace?
[英]Generic type parameter which implements generic interace
在Java应用程序中,我想使用一个通用类型参数,该参数实现一个接口,该接口本身使用一个通用参数。
public interface SuperInterface<T> { ... }
public interface MyInterface extends SuperInterface<MyClass> { ... }
public class Worker<T extends SuperInterface<U>> extends SuperWorker<String, Boolean> {
}
但是,类声明不会那样工作。 T应该是MyInterface类型(或实现SuperInterface的任何其他接口),而U应该是MyClass类型(或根据该接口的任何其他类)。
您必须在顶层声明所有类型参数。 这很烦人,但事实就是如此。
public class Worker<U extends MyClass, T extends SuperInterface<U>> { ...
参数的顺序无关紧要; 你也可以做Worker<T extends..., U extends...>
。 重要的是,每个都在嵌套泛型的顶层声明。
这是一个完整的课程:
public class MyClass {
public interface SuperInterface<T>{}
public interface MyInterface extends SuperInterface<MyClass> {}
public class Worker<U extends MyClass, T extends SuperInterface<U>> {}
public void compileTest() {
// just to make sure the declaration compiles
Worker<MyClass, MyInterface> worker = null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.