Invoking a static method using reflection
// 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.
Fromthe Javadoc of Method.invoke():
If the underlying method is static, then the specified obj argument is ignored. It may be null.
What happens when you
Class klass = ...; Method m = klass.getDeclaredMethod(methodName, paramtypes); m.invoke(null, args)