This code does not work:

public static <T> void doSomething(Class clazz) { List<clazz> list = new ArrayList<>(); } 

How can I put a generic type variable?

  • No Generalizations exist only at compile time, and variables get their values ​​in runtime. - Sergey Gornostaev
  • @SergeyGornostaev rightly) - faoxis
  • Why can't I write a List<Class> list ? - Alexey Shimansky

2 answers 2

This is usually done like this:

 public static <T> void doSomething(Class<T> clazz) { List<T> list = new ArrayList<>(); } 

    You can also pass not a class, but a representative:

     public static <T> void doSomething(T t) List<T> list = new ArrayList<>(); } 

    You can create an object of the desired class using reflection .