2010-03-18 234 views
150

我想調用靜態的main方法。我得到了Class類型的對象,但我無法創建該類的實例,也無法調用static方法main使用反射調用靜態方法

+3

向我們展示的代碼會發生什麼事,請。 – 2010-03-18 04:37:28

回答

213
// String.class here is the parameter type, that might not be the case with you 
Method method = clazz.getMethod("methodName", String.class); 
Object o = method.invoke(null, "whatever"); 

在情況下該方法是私人使用getDeclaredMethod()代替getMethod()。並在方法對象上調用setAccessible(true)

9
String methodName= "..."; 
String[] args = {}; 

Method[] methods = clazz.getMethods(); 
for (Method m : methods) { 
    if (methodName.equals(m.getName())) { 
     // for static methods we can use null as instance of class 
     m.invoke(null, new Object[] {args}); 
     break; 
    } 
} 
+10

爲什麼不用正確的名稱使用getMethod,而不是循環遍歷所有的方法? – mjaggard 2013-04-17 10:54:29

+9

由於getMethod(或getDeclaredMethod)要求您詳細解決參數類型,有時候通過名稱循環和查找方法比使用getMethod更容易。這隻取決於微型效率是否重要 - Java迭代非常快速,除非您在內部循環中調用方法數百萬次,那麼迭代將足夠快 – 2013-09-16 08:32:23

+2

同樣在更真實的情況下,您可能只會找到方法,即使您要使用反射來多次調用它。所以發現它時額外的開銷並不重要。 – RenniePet 2015-11-30 06:54:49

34

Fromthe Method.invoke()的Javadoc中:

如果底層方法是靜態的,則該指定的obj參數將被忽略。它可能爲空。

當你

 
Class klass = ...; 
Method m = klass.getDeclaredMethod(methodName, paramtypes); 
m.invoke(null, args)