Getting generic parameter from supertype class

后端 未结 3 1575
死守一世寂寞
死守一世寂寞 2021-01-21 06:56

Say I have a parent interface/class like so

interface Parent {}

And a number of implementing interfaces that fix the generic type.

3条回答
  •  忘掉有多难
    2021-01-21 07:26

    If you need to do anything non-trivial with generic types at runtime, consider Guava's TypeToken. It can answer your question (and many more!) while addressing some of the nuanced concerns raised by commenters:

    private interface Parent {}
    private interface Intermediate extends Parent {}
    private interface Child extends Comparable, Intermediate> {}
    
    public void exploreGuavaTypeTokens() {
        final TypeToken token = TypeToken.of(Child.class).getSupertype(Parent.class);
        final TypeToken resolved = token.resolveType(Parent.class.getTypeParameters()[0]);
        System.out.println(resolved); // "java.lang.Iterable"
        final Class raw = resolved.getRawType();
        System.out.println(raw); // "interface java.lang.Iterable"
    }
    

提交回复
热议问题