Java:将genric类型从泛型方法传递给新实例一个泛型类(inside方法)

时间:2017-12-04 06:55:57

标签: java generics generic-method

如何在泛型方法中实例化泛型类的新对象,完全与传递(作为类型)的相同类型那个方法

(比如将变量从方法参数传递给类构造函数。)

示例BC都来自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?

    ...
}

0 个答案:

没有答案