当涉及一个实现类(我没有)时,这个问题已经得到解答,但这些方法对我不起作用。
假设我有一个接口(interface)
public interface MySuperInterface<T> {
public void test(T arg);
}
然后是扩展接口(interface)
public interface MyInterface extends MySuperInterface<String> {
}
如果我正在迭代 MyInterface 类的方法,是否可以从 MyInterface 类中获取“测试”方法的实际参数类型(在本例中为 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”。我不应该知道参数将是一个字符串吗?
最佳答案
如果你有显式提供类型参数的实现接口(interface),那么这可以通过反射实现;下面使用的类型是从 java.lang.reflect
导入的。
首先获取第一个超接口(interface)对应的Type
对象。
Type tmi = MyInterface.class.getGenericInterfaces()[0];
在这种情况下,tmi
实际上是一个ParameterizedType
,Type
的子接口(interface)。对其进行转换并获取其类型参数。
ParameterizedType ptmi = (ParameterizedType) tmi;
Type typeArg = ptmi.getActualTypeArguments()[0];
因为您提供了一个类名作为类型参数而不是另一个参数化类型或另一个类型参数,typeArg
是一个 Class
,它实现了 Type
。在这里,它是 java.lang.Class
。
System.out.println(typeArg);
class java.lang.String
关于java - 泛型接口(interface)方法参数的实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51430063/