How can I pass a generic class to a method in Java?

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
}
9
задан Anton 15 April 2011 в 13:12
поделиться