You can genericize the Class to Class<T> and then use T:
public static <T> void createList(Class<T> cls) {
ArrayList<T> = new ArrayList<>();
}
To expand, if you need to find the all instances of a class, or its subclasses, from a list and return the resulting values as a list, you can do:
public static <T> List<T> filterInstancesOf(List<?> original, Class<T> cls) {
List<T> rv = new ArrayList<>();
for (Object o: original) {
if (cls.isInstance(o)) {
rv.add(cls.cast(o));
}
}
return rv;
}
There were suggestions that this cannot be done, and does not make sense to do, but it does have very much sense.
It was also suggested that the original parameter use a bounded type, say List<? super T>. Again this would be useless, it would not add to the type safety, but actually render the method itself less useful.
As it is now, you can use the method to filter instances that implement an interface, for example, assuming we have
List<SomeClass> lst;
...
filterInstancesOf(lst, Serializable.class);
If the method used bounded types, this could not be used, as SomeClass is not the superclass of Serializable.
public static <T> void createList(T c)