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.
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!"
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.
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.
For your stated requirements (dynamically invoke the main method of a random class, with reflection you have alot of unnecessary code.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With