alien01
alien01

Reputation: 1332

Java - Instantiating generic typed class

I have a class for example

public class Example<T> {...}

I would like to instantiate class Example with a specific type class which I know. Pseudocode would look something like that

public Example<T> createTypedExample(Class exampleClass, Class typeClass) {
  exampleClass.newInstance(typeClass); // made-up
}

So that this would give me same result

Example<String> ex = new Example<String>();
ex = createTypedExample(Example.class, String.class);

Is it possible in Java?

Upvotes: 2

Views: 175

Answers (1)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

Since, the return type i.e. the class of the new instance is fixed; there's no need to pass it to the method. Instead, add a static factory method to your Example class as

public class Example<T> {

    private T data;

    static <T> Example<T> newTypedExample(Class<T> type) {
        return new Example<T>();
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

Now, here's how you would create generic Example instances.

// String
Example<String> strTypedExample = Example.newTypedExample(String.class);

strTypedExample.setData("String Data");
System.out.println(strTypedExample.getData()); // String Data

// Integer
Example<Integer> intTypedExample = Example.newTypedExample(Integer.class);

intTypedExample.setData(123);
System.out.println(intTypedExample.getData()); // 123

Upvotes: 1

Related Questions