Retrieving type parameters from an instance of a g

2020-02-08 13:13发布

Given 2 interfaces:

public interface BaseInterface<T> { }
public interface ExtendedInterface<T0, T1> extends BaseInterface<T0> {}

and a concrete class:

public class MyClass implements ExtendedInterface<String, Object> { }

How do I find out the type parameter passed to the BaseInterface interface?

(I can retrieve the ExtendedInterface type parameters by calling something like

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

but I can't spot an easy way to recurse into any base generic interfaces and get anything meaningful back).

9条回答
▲ chillily
2楼-- · 2020-02-08 14:07

I think about the only option I can think of is to inspect a generic method which is declared by BaseInterface, and not overridden.

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-08 14:18

I don't think you can as these are really instance specific not class specific. Consider the following:

List<String>  a = new ArrayList<String>();

The fact that a is generic list of Strings is specific to the instance a and not to the class List. Thus, none of the methods of the List.class object could tell you that the genericized type would be of type String for a. Although MyClass in your example happens to have set values for the genricized types of the interface, i do not think this would be available at the interface Class object instance.

查看更多
登录 后发表回答