Retrieving type parameters from an instance of a generic base interface

前端 未结 9 900
悲&欢浪女
悲&欢浪女 2020-12-14 18:27

Given 2 interfaces:

public interface BaseInterface { }
public interface ExtendedInterface extends BaseInterface {}
         


        
9条回答
  •  Happy的楠姐
    2020-12-14 18:30

    This is difficult to solve using Java Reflection API because one needs to resolve all encountered type variables. Guava since version 12 has TypeToken class which contains fully resolved type info.

    For your example, you can do:

    TypeToken token = TypeToken.of(MyClass.class);
    ParameterizedType type =
        (ParameterizedType) token.getSupertype(BaseInterface.class).getType();
    Type[] parameters = type.getActualTypeArguments();
    

    Still you need to remember that this only works for cases when MyClass is not generic itself. Otherwise the value of type parameters is not available at runtime due to type erasure.

提交回复
热议问题