Get type of a generic parameter in Java with reflection

后端 未结 18 2229
死守一世寂寞
死守一世寂寞 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:19

    As pointed out by @bertolami, it's not possible to us a variable type and get its future value (the content of typeOfList variable).

    Nevertheless, you can pass the class as parameter on it like this:

    public final class voodoo {
        public static void chill(List aListWithTypeSpiderMan, Class clazz) {
            // Here I'd like to get the Class-Object 'SpiderMan'
            Class typeOfTheList = clazz;
        }
    
        public static void main(String... args) {
            chill(new List(), Spiderman.class );
        }
    }
    

    That's more or less what Google does when you have to pass a class variable to the constructor of ActivityInstrumentationTestCase2.

提交回复
热议问题