I would like to do the following (which doesn’t work, it is just to explain the concept). Any idea how to do it?
Class type;
if (/* something */)
type = String.class;
else
type = Boolean.class;
return new ArrayList<type>();
ArrayList<type> doesn’t work. I tried with type.getClass(), doesn’t work either.
Wrap it into the method, pass the type as generic
Classand let Java do the rest for you. No need for any conditional branching.Then you can use it like this:
Bear in mind that
Tdoes not have to be specified at the generic class level. You can specify generic type for the method and therefore make it a generic method as in the example code.