Home > Java > javaTutorial > body text

How to Execute a Java Application in a Separate Process for Cross-Platform Compatibility?

Mary-Kate Olsen
Release: 2024-11-03 10:23:29
Original
301 people have browsed it

How to Execute a Java Application in a Separate Process for Cross-Platform Compatibility?

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();
    }
}
Copy after login

Usage:

int status = JavaProcess.exec(MyClass.class, args);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!