gpt4 book ai didi

java - 在同一项目中加载带有参数的类

转载 作者:行者123 更新时间:2023-11-30 04:17:29 25 4
gpt4 key购买 nike

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

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

这工作得很好,但我想在不输入命令行的情况下执行此操作,有什么办法可以从 jar 中使用 Xbootclasspath 吗?

谢谢。

最佳答案

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

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

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
}
}

关于java - 在同一项目中加载带有参数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17981088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com