Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java call main() method of a class using reflection

Tags:

I need to call the main method of a Java class from another main method using reflection.

Usage of reflection is a must so as to remove compile time dependency of the main class being called. Straightforward approach is not yielding as it recognizes only 'public' and 'non-static' method. Suggestions?

like image 602
anotherNovice1984 Avatar asked Feb 12 '11 19:02

anotherNovice1984


People also ask

How do you call a main method in Java?

Call a Method Inside 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!"

How do I invoke a reflection API method?

First, to find the main() method the code searches for a class with the name "main" with a single parameter that is an array of String Since main() is static , null is the first argument to Method. invoke() . The second argument is the array of arguments to be passed.

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

Shouldn't be any more complicated than calling any other function:

public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {     Class<?> cls = Class.forName("pkg1.pkg2.classname");     Method meth = cls.getMethod("main", String[].class);     String[] params = null; // init params accordingly     meth.invoke(null, (Object) params); // static method doesn't have an instance } 

But I don't really see many uses for that, the only thing it buys you is that you can compile the program without linking the other one as long as you never use that specific code path, but if that's what you need, here we go ;)

like image 106
Voo Avatar answered Nov 15 '22 05:11

Voo