1

好吧,我正在尝试从我的项目中 Xbootclasspath 一个 jar。目前我必须通过命令行使用以下命令加载我的应用程序:

java -Xbootclasspath/p:canvas.jar -jar application.jar

这工作得很好,但我想这样做而不必输入命令行,有没有办法可以从 jar 中进行 Xbootclasspath?

谢谢。

4

2 回答 2

2

最明确的解决方案是有两个主要类。

您的第一个类(已命名Boot或类似)将是应用程序的外部入口点,如 jar 清单中设置的那样。此类将形成必要的运行时命令Application,以使用 Xboot 参数启动您的实际主类(命名或类似)。

public class Boot {

    public static void main(String[] args) {
        String location = Boot.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        location = URLDecoder.decode(location, "UTF-8").replaceAll("\\\\", "/");
        String app = Application.class.getCanonicalName();
        String flags = "-Xbootclasspath/p:canvas.jar";
        boolean windows = System.getProperty("os.name").contains("Win");

        StringBuilder command = new StringBuilder(64);
        if (windows) {
            command.append("javaw");
        } else {
            command.append("java");
        }
        command.append(' ').append(flags).append(' ');
        command.append('"').append(location).append('"');
        // append any necessary external libraries here
        for (String arg : args) {
             command.append(' ').append('"').append(arg).append('"');
        }

        Process application = null;
        Runtime runtime = Runtime.getRuntime();
        if (windows) {
            application = runtime.exec(command.toString());
        } else {
            application = runtime.exec(new String[]{ "/bin/sh", "-c", command.toString() });
        }

        // wire command line output to Boot to output it correctly
        BufferedReader strerr = new BufferedReader(new InputStreamReader(application.getErrorStream()));
        BufferedReader strin = new BufferedReader(new InputStreamReader(application.getInputStream()));
        while (isRunning(application)) {
            String err = null;
            while ((err = strerr.readLine()) != null) {
                System.err.println(err);
            }
            String in = null;
            while ((in = strin.readLine()) != null) {
                System.out.println(in);
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException ignored) {
            }
        }
    }

    private static boolean isRunning(Process process) {
        try {
            process.exitValue();
        } catch (IllegalThreadStateException e) {
            return true;
        }
        return false;
    }
}

你的Application班级运行你的实际程序:

public class Application {

    public static void main(String[] args) {
        // display user-interface, etc
    }
}
于 2013-07-31T21:58:58.523 回答
0

感觉很恶心,但你能做一个 Runtime.exec 调用 java 提供的选项和一个新参数(以及一些寻找它的条件代码),以防止产生新进程的递归循环吗?

于 2013-07-31T21:57:59.780 回答