Retrieving type parameters from an instance of a generic base interface

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

Given 2 interfaces:

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


        
9条回答
  •  一向
    一向 (楼主)
    2020-12-14 18:44

    This problem is not easy to fully solve in general. For example, you also have to take type parameters of the containing class into account if it's an inner class,...

    Because reflection over generic types is so hard using just what Java itself provides, I wrote a library that does the hard work: gentyref. See http://code.google.com/p/gentyref/ For your example, using gentyref, you can do:

    Type myType = MyClass.class;
    
    // get the parameterized type, recursively resolving type parameters
    Type baseType = GenericTypeReflector.getExactSuperType(myType, BaseInterface.class);
    
    if (baseType instanceof Class) {
        // raw class, type parameters not known
        // ...
    } else {
        ParameterizedType pBaseType = (ParameterizedType)baseType;
        assert pBaseType.getRawType() == BaseInterface.class; // always true
        Type typeParameterForBaseInterface = pBaseType.getActualTypeArguments()[0];
        System.out.println(typeParameterForBaseInterface);
    }
    

提交回复
热议问题