[英]How to run java command through code without creating a new process?
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
也許您可以使用ObjectInputStream將類讀入Process
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.