[英]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.