[英]How To add an External jar File to the ClassPath Dynamically at runtime?
I want to add a jar File to my project's classpath dynamically using java code if it is possible , I want to use external jar files and load their classes the execute them as Beans later (Spring framework). 我希望使用java代码动态地将jar文件添加到我的项目的类路径中,如果可能的话,我想使用外部jar文件并加载它们的类,将它们作为Beans稍后执行(Spring框架)。
Thanks :) 谢谢 :)
URLClassLoader child = new URLClassLoader (myJar.toURL(), this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);
Source: https://stackoverflow.com/a/60775/1360074 资料来源: https : //stackoverflow.com/a/60775/1360074
You can try something like this, but it requires you to know, where exactly your JARs
are located. 你可以试试这样的东西,但它需要你知道你的JARs
里。
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {myJarFiles});
Class myClass = cl.loadClass("com.mycomp.proj.myclass");
Method printMeMethod = myClass.getMethod("printMe", new Class[] {String.class, String.class});
Object myClassObj = myClass.newInstance();
Object response = printMeMethod.invoke(myClassObj, "String1", "String2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.