如何在泛型方法中实例化泛型类的新对象,完全与传递(作为类型)的相同类型那个方法?
(比如将变量从方法参数传递给类构造函数。)
示例:B
和C
都来自A
。我希望 {em} T
的新实例(在GenericClass
中实例化并命名为genericMethod
)为{{1} }或genericClassT
(取决于B
调用)。
C
完整测试(以下代码genericMethod
已重命名以获得更好的含义):
class A {}
class B extends A {}
class C extends A {}
abstract class GenericClass<T extends A> { ... }
public static void main(String[] args) {
...
genericMethod(B.class);
genericMethod(C.class);
}
<T extends A> boolean genericMethod(Class<T> tClass) {
final GenericClass<T> genericClassT = new GenericClass<T>() {
@Override void test(T input) {}
}; // THE PROBLEM IS HERE:
// The T(s) in this statement aren't the same T that passed to method!
// They Are `A` always (not `B` or `C`). How can I pass the same T that passed to the method?
...
}