如何在不创建新进程的情况下通过代码运行java命令?

时间:2015-07-31 17:35:34

标签: java

Runtime.getRuntime().exec("....")

ProcessBuilder pb = new ProcessBuilder("java", "-server", "-jar", "yourJar.jar");
Process p = pb.start();

以上两种执行命令的方法创建了一个运行命令的新进程。

有没有办法在同一个过程中执行命令,而无需创建新命令?

2 个答案:

答案 0 :(得分:3)

正如@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

答案 1 :(得分:0)

也许您可以使用ObjectInputStream将进程读入进程