views:

461

answers:

3

How do i call a Java command from a stand alone java program.

I understand that Runtime.getRuntime().exec("cmd c/ javac <>.java"); would work. However, this would be platform specific.

Any other APIs available that could make it work in j2sdk1.4 ?

A: 

When you leave the JVM and move to system commands, then you have to deal with the platform specific commands yourself. The JVM offers a good way for abstraction, so why move away?

If you want to execute java specific binaries, check out the ant libraries of java. You can execute ant scripts from java which execute platform depending commands.

Martin K.
+2  A: 

If you can run everything in the same JVM, you could do something like this:

public class Launcher {
    ...
    public static void main(String[] args) throws Exception {
        launch(Class.forName(args[0]), programArgs(args, 1));
    }

    protected static void launch(Class program, String[] args) throws Exception {
        Method main = program.getMethod("main", new Class[]{String[].class});
        main.invoke(null, new Object[]{args});
    }

    protected static String[] programArgs(String[] sourceArgs, int n) {
        String[] destArgs = new String[sourceArgs.length - n];
        System.arraycopy(sourceArgs, n, destArgs, 0, destArgs.length);
        return destArgs;
    }

And run it with a command line like this:

java Launcher OtherClassWithMainMethod %CMD_LINE_ARGS%
A_M
+2  A: 

Calling Runtime.getRuntime().exec() is not only platform specific, it is extremely inefficient. It will result in spawning a brand new shell and an entire jvm which could potentially be very expensive depending on the dependencies of this application (no pun intended).

The best way to execute "external" Java code would be to place it in your CLASSPATH. If you must call an application's main method you can simply import and call the method directly. This could be done like so:

import my.externals.SomeMain

// call as if we are running from console
SomeMain.main(new String[] {"some", "console", "arguments"})

Of course, the best case scenario would be to simply use this as an external library and access the code you need without having to call SomeMain.main(). Adhering to best practices and writing proper encapsulated modular objects allows for much greater portability and ease of use when being used by other applications.

jcm