Suppose we have a function that creates objects given a particular class:
public static <T> T createObject(Class<T> generic) {
try {
return generic.newInstance();
} catch (Exception ex) {
return null;
}
}
We can use the function easily to create instances of non-generic types.
public static void main(String[] args) {
Foo x = createObject(Foo.class);
}
Is it possible to do the same thing with a generic type?
public static void main(String[] args) {
ArrayList<Foo> x = createObject(ArrayList<Foo>.class); // compiler error
}