I want to write a method that gets a class and an Array of strings and call the main method of the class with the array given.
Something like this:
pub
Given below is how you should define the method:
public static void executeMain(Class<?> cls, Object[] args) {
try {
Object[] param = { args };
Method method = cls.getDeclaredMethod("main", args.getClass());
method.invoke(cls, param);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
Assignment1.java:
import java.util.Arrays;
public class Assignment1 {
public static void main(String[] args) {
if (args == null) {
System.out.println("Welcome to Assignment1");
} else {
System.out.println("Arguments to main in Assignment1: " + Arrays.toString(args));
}
}
}
Assignment2.java
import java.util.Arrays;
public class Assignment2 {
public static void main(String[] args) {
if (args == null) {
System.out.println("Welcome to Assignment2");
} else {
System.out.println("Arguments to main in Assignment2: " + Arrays.toString(args));
}
}
}
Test class:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
Assignment1.main(null);
Assignment1.main(new String[] { "Hello", "World" });
Assignment2.main(null);
Assignment2.main(new String[] { "Hello", "World" });
executeMain(Assignment1.class, new String[] { "Good", "Morning" });
executeMain(Assignment2.class, new String[] { "Good", "Morning" });
}
public static void executeMain(Class<?> cls, Object[] args) {
try {
Object[] param = { args };
Method method = cls.getDeclaredMethod("main", args.getClass());
method.invoke(cls, param);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
}
Output:
Welcome to Assignment1
Arguments to main in Assignment1: [Hello, World]
Welcome to Assignment2
Arguments to main in Assignment2: [Hello, World]
Arguments to main in Assignment1: [Good, Morning]
Arguments to main in Assignment2: [Good, Morning]
Check this to learn more about Java Reflection API.