Executing a Java Application in a Separate Process, Simplified
The ability to execute a Java application in a separate process, independent of its location, is a valuable feature for cross-platform compatibility. However, traditional approaches using Runtime.getRuntime().exec(COMMAND) can be platform-specific.
To address this issue, consider the following enhanced solution:
public final class JavaProcess { private JavaProcess() {} public static int exec(Class klass, List<String> args) throws IOException, InterruptedException { // Determine platform-independent paths String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); String className = klass.getName(); // Create process builder ProcessBuilder builder = new ProcessBuilder(); // Set command and arguments builder.command().addAll(Arrays.asList(javaBin, "-cp", classpath, className)); builder.command().addAll(args); // Execute and return exit status Process process = builder.inheritIO().start(); process.waitFor(); return process.exitValue(); } }
Usage:
int status = JavaProcess.exec(MyClass.class, args);
This approach leverages the Java system properties to obtain necessary paths and utilizes a ProcessBuilder for platform-independent process creation. It accepts the fully qualified class name and provides the desired platform-agnostic behavior.
The above is the detailed content of How to Execute a Java Application in a Separate Process for Cross-Platform Compatibility?. For more information, please follow other related articles on the PHP Chinese website!