views:

91

answers:

3

hi, in my project 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".Help

A: 

hi,

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;
    }
}
Frostman
+1  A: 
// 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.

Adeel Ansari
A: 

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)
atk