Specifying a generic type in java from Class object
generics, java, reflection
Solution
<T extends Number> ArrayList<T> createAList(Class<T> type)
{
ArrayList<T> toReturn = new ArrayList<>();
return toReturn;
}
ArrayList<Integer> intList = createAList(Integer.class);
Problem
Why this is wrong: ``` Class<? extends Number> type = Integer.class; ArrayList<type> = new ArrayList<>(); ``` ? Is there no way to instantiate a class of a specific type given a class object? Obviously I would never do that directly, that is just an example to show what is needed. In the actual code I need I don't know the name of the type. For example ``` public void createAList(Class<? extends Number> type) { ArrayList<type> toReturn = new ArrayList<>(); return toReturn; } ```