简体   繁体   English

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

[英]How to run java command through code without creating a new process?

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

and

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

The above 2 ways of executing a command create a new process for running the command. 上述两种执行命令的方法创建了一个运行命令的新进程。

Is there a way to execute the command in the same process, without creating a new one? 有没有办法在同一个过程中执行命令,而不创建新的命令?

As @soong commented, you could manually load your JAR and the classes you need, and then call the main method by reflection. 正如@soong评论的那样,您可以手动加载JAR和所需的类,然后通过反射调用main方法。 You can achieve this with something like this: 您可以通过以下方式实现此目的:

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

也许您可以使用ObjectInputStream将类读入Process

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM