3 回答

TA貢獻1963條經驗 獲得超6個贊
// 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)方法對象。

TA貢獻1796條經驗 獲得超10個贊
從Method.invoke()的Javadoc中:
如果基礎方法是靜態的,則忽略指定的obj參數。它可以為空。
當你會發生什么
類別klass = ...;
方法m = klass.getDeclaredMethod(methodName,paramtypes);
m.invoke(null,args)

TA貢獻1773條經驗 獲得超3個贊
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;
}
}
添加回答
舉報