Retrieving type parameters from an instance of a generic base interface

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

Given 2 interfaces:

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


        
9条回答
  •  -上瘾入骨i
    2020-12-14 18:46

    I don't think there's an direct way of getting the generic type of the base interface.

    One way would be to declare a method in the interface like this:

    public interface BaseInterface {
        Class getGenericClass();
    }
    

    Also, I don't know what kind of control you have over these classes. You can always assert that all implementers have the base interface explicitly declared like:

    public class MyClass implements ExtendedInterface, BaseInterface{ }
    

    and

    MyClass.class.getGenericInterfaces()[1].getActualTypeArguments()[0]
    

提交回复
热议问题