通用接口方法参数的实际类型

时间:2018-07-19 18:59:38

标签: java class object generics reflection

当涉及到一个实现类(我没有)时,已经回答了这个问题,但是那些方法对我不起作用。

假设我有一个界面

public interface MySuperInterface<T> {
    public void test(T arg);
}

然后是扩展接口

public interface MyInterface extends MySuperInterface<String> {

}

如果我要迭代MyInterface类的方法,是否可以从MyInterface类获取'test'方法的参数的实际类型(在本例中为String)?

for (Method method : MyInterface.class.getMethods())
{
    for (Parameter parameter : method.getParameters())
    {
        final Class<?> paramClass = parameter.getType();
        System.out.println(paramClass);
    }
}

上面的代码将输出'class java.lang.Object'。我不应该知道该参数将是一个字符串吗?

2 个答案:

答案 0 :(得分:0)

如果您具有显式提供type参数的实现接口,则可以通过反射实现;以下使用的类型是从java.lang.reflect导入的。

首先获取与第一个超级接口相对应的Type对象。

Type tmi = MyInterface.class.getGenericInterfaces()[0];

在这种情况下,tmi实际上是ParameterizedType的{​​{1}}子接口。强制转换并获取其类型参数。

Type

因为您提供了一个类名作为类型参数,而不是另一个参数化类型或另一个类型参数,所以ParameterizedType ptmi = (ParameterizedType) tmi; Type typeArg = ptmi.getActualTypeArguments()[0]; typeArg,它实现了Class。这里是Type

java.lang.Class

答案 1 :(得分:0)

您可以使用我的实用程序类GenericUtil。它可以解析通用类型。

Method m = MyInterface.class.getMethod("test", Object.class); // get the method
Type p = m.getGenericParameterTypes()[0]; // get the generic type 'T'
Map<TypeVariable<?>, Type> map = GenericUtil.getGenericReferenceMap(MyInterface.class); // get generic map of the class's context
System.out.println(map.get(p)); // get actual type for 'T'

输出

class java.lang.String