How to get type parameter values using java reflection?

前端 未结 2 931
温柔的废话
温柔的废话 2021-02-20 02:04
interface Foo { ... }
class Bar implements Foo { ... }

I\'ve got a Bar object. How to get the value of T

相关标签:
2条回答
  • 2021-02-20 02:49

    If you already have Guava on the classpath, this is a bit more robust as you specify the interface/superclass by type rather than index.

    TypeToken<?> baz = TypeToken.of(Bar.class).resolveType(Foo.class.getTypeParameters()[0]);
    System.out.println(baz.getRawType()); // class Baz
    
    0 讨论(0)
  • 2021-02-20 02:51
    Type type = bar.getClass().getGenericInterfaces()[0];
    
    if (type instanceof ParameterizedType) {
        Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0];
        System.out.println(actualType);
    }
    

    Of course, in the general case, you should iterate over the array, rather than assuming it has excatly one element ([0]). With the above example, you can cast actualType to java.lang.Class. In other cases it may be different (see comment by meriton)

    0 讨论(0)
提交回复
热议问题