1

Let's say I have String type = "Integer" for example, and I have on the other side a public class MyType<T> with a constructor public MyType(){} How can I use the java reflection newInstance method in order to be able to do something along the lines:

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

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

}
  • Generics are compile-time type checking. Reflection is a run-time construction. At run-time, there will be one constructor which takes as a parameter an object of the erased type (the first bound if there is one, else Object) – Michael Feb 13 '19 at 10:37

1 Answers1

1

You don't need "String type" parameter for this, you can just use following code:

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<>();
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59