Launch An Application Within An Application
Java: How To
While you can exec("java myaotherapp"), 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");
}
}
|
To call the above application from another
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 above example is used when the class is hard-coded.
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};
try
{
Class.forName(name).
getDeclaredMethod("main", params).
invoke(null, new Object[] {new String[] {}});
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
|