Java - Creating an object extending List

casting, constructor, generics, java, list

Solution

You can't do that. Generics have no business at runtime, so you can't create parameterized instance at runtime using reflection. At runtime, `LinkedList<Intege>` is just a `LinkedList`. The type information - `Integer` is erased at compile time through "type erasure". The point is, why would you like to do that?

Problem

How can I create a list with a specified type argument? For example: ``` LinkedList<Integer> list = createList(LinkedList.class, Integer.class); ``` I've tried creating a method for it, but the method doesn't include the type argument when creating the new instance. ``` public static <T, L extends List<T>> L createList(Class<L> listClazz, Class<T> valueClazz) throws Exception { return listClazz.getConstructor().newInstance(); //Instead of // new L<T>(); //does // new L(); } ``` I hope my question is clear enough, thank you for any help.

Original source