How to get parametrized Class instance

Tags: generics java
By : Michal
Source: Stackoverflow.com
Question!

Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear.

What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet:

public class GenTest {
    static <T> T instantiate(Class<T> clazz) throws Exception {
        return clazz.newInstance();
    }
    public static void main(String[] args) throws Exception {
        // Is there a way to avoid waring on the line below
        // without using  @SuppressWarnings("unchecked")?
        // ArrayList.class is Class<ArrayList>, but I would like to
        // pass in Class<ArrayList<String>>
        ArrayList<String> l = GenTest.instantiate(ArrayList.class);
    }
}

I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions.

By : Michal


Answers

The only thing you can do is instantiate List<String> directly and call its getClass():

instantiate(new List<String>() { ... }.getClass());

For types with multiple abstract methods like List, this is quite awkward. But unfortunately, calling subclass constructors (like new ArrayList<String>) or factory methods (Collections.<String>emptyList()) don't work.

By : thSoft


This video can help you solving your question :)
By: admin