Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call main() method of a class using reflection in java

When calling the main method of a Java class from another main method using reflection,

Class thisClass = loader.loadClass(packClassName);
Method thisMethod = thisClass.getDeclaredMethod("main",String[].class);

thisMethod.invoke(null, new String[0]);

Should i create newInstance() or simply call main() as it is static.

like image 533
Akhilesh Dhar Dubey Avatar asked Mar 23 '13 01:03

Akhilesh Dhar Dubey


People also ask

How do you call a main method in Java?

Call a MethodInside main , call the myMethod() method: public class Main { static void myMethod() { System. out. println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"

Which method is used to get methods using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.

Can I call Main method from another class?

Solution: Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.


1 Answers

For your stated requirements (dynamically invoke the main method of a random class, with reflection you have alot of unnecessary code.

  • You do not need to invoke a constructor for the class
  • You do not need to introspect the classes fields
  • Since you are invoking a static method, you do not even need a real object to invoke the method on

You can adapt the following code to meet your needs:

try {
    final Class<?> clazz = Class.forName("blue.RandomClass");
    final Method method = clazz.getMethod("main", String[].class);

    final Object[] args = new Object[1];
    args[0] = new String[] { "1", "2"};
    method.invoke(null, args);
} catch (final Exception e) {
    e.printStackTrace();
}
like image 171
Perception Avatar answered Sep 21 '22 04:09

Perception