In this blog post, I will show you how to call a main from inside a main method in java using reflection
Let’s start from creating a simple class Hello.java
as shown below,
public class Hello { public static void main(String[]args){ System.out.println("Hello"); } }
Now, Let’s create another class Test.java
which also has a main method and let’s call the main from Hello here,
import java.lang.reflect.Method; public class Test { public static void main(String []args) { try { Class<?> cls = Class.forName("Hello"); //System.setProperty(FILENAME, FILEPATH); Method meth = cls.getMethod("main", String[].class); meth.invoke(null,(Object)args); } catch (Exception e) { e.printStackTrace(); } } }
Optionally you can useSystem.setProperty
to pass vm options
Output:
Hello