Instantiating a generic class in Java

generics, java

Solution

One option is to pass in `Bar.class` (or whatever type you're interested in - any way of specifying the appropriate `Class<T>` reference) and keep that value as a field:

public class Test {
    public static void main(String[] args) throws IllegalAccessException,
            InstantiationException {
        Generic<Bar> x = new Generic<>(Bar.class);
        Bar y = x.buildOne();
    }
}

public class Generic<T> {
    private Class<T> clazz;

    public Generic(Class<T> clazz) {
        this.clazz = clazz;
    }

    public T buildOne() throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}

public class Bar {
    public Bar() {
        System.out.println("Constructing");
    }
}

Another option is to have a "factory" interface, and you pass a factory to the constructor of the generic class. That's more flexible, and you don't need to worry about the reflection exceptions.

Problem

I know Java's generics are somewhat inferior to .Net's. I have a generic class `Foo<T>`, and I really need to instantiate a `T` in `Foo` using a parameter-less constructor. How can one work around Java's limitation?

Original source

Related problems