I have a test.jar
. This jar
has only one class. All it does is delete a folder
import java.io.File;
public class Test {
public static void main(String[] args) {
File fileTest = new File("C:\\Users\\...\\test");
fileTest.delete();
}
}
I need to execute this external test.jar
from other java application
This is what I tried
ClassLoader pluginLoader = new PluginClassLoader(new URL("file:\\\\C:\\Users\\ . . .\\test.jar"));
Class<?> pluginClass = pluginLoader.loadClass("Test");
Plugin plugin = (Plugin) pluginClass.newInstance();
pluginClass.getMethod("main"); // trying to get main method but it throw no such method exception
The correct way to implement a plugin architecture is with the ServiceLoader class. But your case seems to be a much simpler one, since your Test
class only has one static method.
First, the main
method of class Test
is static
. This means no instance needs to be created in order to call it, so you should remove the call to pluginClass.newInstance()
.
Second, a method in Java is defined by its signature. The signature is identified by both the method name and the types of the method arguments. There is no method with the signature main()
, but there is a method with the signature main(String[])
.
You need to specify the full signature of the method you're requesting:
pluginClass.getMethod("main", String[].class);
Finally, you can invoke it:
Method main = pluginClass.getMethod("main", String[].class);
main.invoke(null, new Object[] { new String[0] });
The first argument to main.invoke
is null, because it's a static
method and there is no specific instance required.
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("java -jar test.jar");
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.