如何在运行时动态地将外部jar文件添加到ClassPath?

我想使用java代码动态地将jar文件添加到我的项目的类路径中,如果可能的话,我想使用外部jar文件并加载它们的类,然后将它们作为Beans执行(Spring框架)。

谢谢 :)

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); 

资料来源: https : //stackoverflow.com/a/60775/1360074

你可以试试这样的东西,但它要求你知道你的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");