Launch an application from another applicationTag(s): IO Language
While you can exec("java myanotherapp"), it is more appropriate to instanciate and called the main method of the other application.
For example, take this simple application :
public class Program2 {
public static void main(String arg[]) {
System.out.println("Hello from Program2");
}
}
public class Program1a {
public static void main(String arg[]) {
System.out.println("Hello from Program1a");
new Thread(){
public void run() {
Program2.main(new String[]{});}
}.start();
}
}
The dynamic version is little more tricky.
public class Program1b {
public static void main(String arg[]) {
System.out.println("Hello from Program1b");
new Program1b().execute("Program2");
}
public void execute(String name) {
Class params[] = {String[].class};
// if you need parameters
// String[] args = new String[] { "Hello", "world" };
// Class params[] = new Class[] { args.getClass() });
try {
Class.forName(name).
getDeclaredMethod("main", params).
invoke(null, new Object[] {new String[] {}});
}
catch(Exception e){ e.printStackTrace();}
}
}Launch many programs using Thread and use join() to wait for the completion.
[Program2.java]
public class Program2 {
public static void main(String arg[]) {
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
}
}
[Program1a.java]
public class Program1a {
public static void main(String arg[]) throws Exception{
System.out.println("Hello from Program1a");
Thread t1 = new Thread(){
public void run() {
Program2.main(new String[]{});}
};
t1.start();
t1.join();
System.out.println("Hello from Program1a");
}
}
C:\>java Program1a Hello from Program1a Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program2 Hello from Program1a
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com