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
.
This question is related to
java
reflection
static
public class Add {
static int add(int a, int b){
return (a+b);
}
}
In the above example, 'add' is a static method that takes two integers as arguments.
Following snippet is used to call 'add' method with input 1 and 2.
Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);
Reference link.
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)
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;
}
}
Source: Stackoverflow.com