首页 > 解决方案 > 如何使用反射来执行泛型构造函数

问题描述

假设我有String type = "Integer"例如,我在另一边有一个public class MyType<T>带有构造函数的 apublic MyType(){} 我如何使用 java 反射 newInstance 方法以便能够执行以下操作:

public static MyType<?> create(String type){

    return /*new MyType<Integer>() if type was "Integer", etc*/;

}

标签: javagenericsreflection

解决方案


您不需要“字符串类型”参数,您可以使用以下代码:

public static void main(final String[] args)
{
    final MyType<Integer> myType1 = create();
    myType1.v = 1;
    final MyType<String> myType2 = create();
    myType2.v = "1";
    System.out.print(myType1);
    System.out.print(myType2);
}

public static class MyType<T>
{
    T v;
}

public static <K> MyType<K> create()
{
    return new MyType<>();
}

推荐阅读