简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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