Anthony Cacapone
Anthony Cacapone

Reputation: 13

How to use reflection in order to execute a generic constructor

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*/;

}

Upvotes: 1

Views: 46

Answers (1)

Slava Vedenin
Slava Vedenin

Reputation: 60244

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<>();
}

Upvotes: 1

Related Questions