Get type of a generic parameter in Java with reflection

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

    The quick answer the the Question is no you can't, because of Java generic type erasure.

    The longer answer would be that if you have created your list like this:

    new ArrayList(){}
    

    Then in this case the generic type is preserved in the generic superclass of the new anonymous class above.

    Not that I recommend doing this with lists, but it is a listener implementation:

    new Listener() { public void doSomething(Type t){...}}
    

    And since extrapolating the generic types of super classes and super interfaces change between JVMs, the generic solution is not as straight forward as some answers might suggest.

    Here is now I did it.

提交回复
热议问题