Invoking a static method using reflection

Steven picture Steven · Mar 18, 2010 · Viewed 152.9k times · Source

I want to invoke the main method which is static. I got the object of type Class, but I am not able to create an instance of that class and also not able to invoke the static method main.

Answer

Adeel Ansari picture Adeel Ansari · Mar 18, 2010
// 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");

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.