Get type of a generic parameter in Java with reflection

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

    Appendix to @DerMike's answer for getting the generic parameter of a parameterized interface (using #getGenericInterfaces() method inside a Java-8 default method to avoid duplication):

    import java.lang.reflect.ParameterizedType; 
    
    public class ParametrizedStuff {
    
    @SuppressWarnings("unchecked")
    interface Awesomable {
        default Class parameterizedType() {
            return (Class) ((ParameterizedType)
            this.getClass().getGenericInterfaces()[0])
                .getActualTypeArguments()[0];
        }
    }
    
    static class Beer {};
    static class EstrellaGalicia implements Awesomable {};
    
    public static void main(String[] args) {
        System.out.println("Type is: " + new EstrellaGalicia().parameterizedType());
        // --> Type is: ParameterizedStuff$Beer
    }
    

提交回复
热议问题