[英]type of parameter when using java reflection
在庫中,有一個函數將Class對象作為參數:
public void libMethod(Class<?> cls){...}
我需要以Java Reflection方式調用此庫函數。
例如我有一個課:
public MySchool extends School{...}
我想將MySchool
類傳遞給庫函數。 我試過了:
//I can successfully get library class & a instance of it
Class<?> libClass = GET_LIB_CLASS();
//How can I define the type for the parameter?
Method m = libClass.getDeclaredMethod("libMethod", new Class[]{MySchool.class});
return m.invoke(libClass.newInstance(), MySchool.class);
我以上述方式嘗試過,但沒有用。
我如何以上述Java反射方式定義參數的類型?
請注意,您的方法采用Class<?>
類型的參數。 將傳遞給自變量Class#getDeclaredMethod()
是陣列Class
的格式參數類型的方法的,在這種情況下將是實例Class.class
,而不是MySchool.class
。
因此,您應該將方法獲取為:
Method m = libClass.getDeclaredMethod("libMethod", new Class[]{Class.class});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.