繁体   English   中英

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

[英]Actual type of generic interface method parameter

涉及实施课程时我已经回答了这个问题(我没有),但这些方法对我不起作用。

假设我有一个界面

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'。 我不应该告诉参数将是一个字符串吗?

如果你有明确提供类型参数的实现接口,那么这可以通过反射实现; 使用的以下类型是从java.lang.reflect导入的。

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

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

在这种情况下, tmi实际上是ParameterizedTypeType的子接口。 抛出它并得到它的类型参数。

ParameterizedType ptmi = (ParameterizedType) tmi;
Type typeArg = ptmi.getActualTypeArguments()[0];

因为您提供了类名作为类型参数而不是其他参数化类型或其他类型参数,所以typeArg是一个实现TypeClass 在这里,它是java.lang.Class

System.out.println(typeArg);

class java.lang.String

您可以使用我的实用程序类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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM