Runtime.getRuntime().exec("....")
和
ProcessBuilder pb = new ProcessBuilder("java", "-server", "-jar", "yourJar.jar");
Process p = pb.start();
以上两种执行命令的方式创建了一个新的进程来运行命令。
有没有办法在同一个进程中执行命令,而无需创建新进程?
最佳答案
正如@soong 评论的那样,您可以手动加载您的 JAR 和您需要的类,然后通过反射调用 main
方法。您可以通过以下方式实现此目的:
// load your JAR file as a File instance
String myJarPath = "C:\\somefolder\\someOtherFolder\\MyJar.jar";
File myJarFile = new File(myJarPath);
// create a new class loader based on your JAR's URL
URLClassLoader classLoader = new URLClassLoader(new URL[]{myJarFile.toURI().toURL()});
// load the class with the main method
Class<?> classToLoad = classLoader.loadClass("MyClass");
// get the main method
Method method = classToLoad.getMethod("main", String[].class);
// invoke it
String args[] = {"arg1", "arg2"}; // args to pass to the main method, it can be null
method.invoke(null, (Object) args); // first parameter is null because main is static
关于java - 如何在不创建新进程的情况下通过代码运行 java 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31752001/