[英]How to identify if a java method is generic using reflection?
如何使用反射检查示例代码中的getQueue()
是否通用? 一种方法是遍历参数类型并返回类型,并检查它们是否是TypeVariable
实例。 我正在寻找更简单的东西。
Class SomeClass {
<V> Queue<V> getQueue();
}
您不需要查找方法的参数类型或返回类型来确定是否具有类型参数,因为类Method
的方法getTypeParameters
返回类型参数的数组。
这是显示使用此方法的示例。 由于术语令人难以置信,因此我在这里还显示了其他2种方法的使用。
public class SomeClass {
<V, U> Queue<V> someMethod(String str, int a, List<U> list) {
return null;
}
public static void main(String[] args) throws Exception {
Method method = SomeClass.class.getDeclaredMethod("someMethod", String.class, int.class, List.class);
TypeVariable<Method>[] typeParameters = method.getTypeParameters();
System.out.println(typeParameters.length); // Prints "2"
System.out.println(typeParameters[0].getName()); // Prints "V"
Class<?>[] parameterTypes = method.getParameterTypes();
System.out.println(Arrays.toString(parameterTypes)); // Prints [class java.lang.String, int, interface java.util.List]
Type[] genericParameterTypes = method.getGenericParameterTypes();
System.out.println(genericParameterTypes[2].getTypeName()); // Prints java.util.List<U>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.