Get type of a generic parameter in Java with reflection

后端 未结 18 1961
死守一世寂寞
死守一世寂寞 2020-11-22 05:56

Is it possible to get the type of a generic parameter?

An example:

public final class Voodoo {
    public static void chill(List aListWithTy         


        
18条回答
  •  [愿得一人]
    2020-11-22 06:32

    Because of type erasure the only way to know the type of the list would be to pass in the type as a parameter to the method:

    public class Main {
    
        public static void main(String[] args) {
            doStuff(new LinkedList(), String.class);
    
        }
    
        public static  void doStuff(List list, Class clazz) {
    
        }
    
    }
    

提交回复
热议问题