How To add an External jar File to the ClassPath Dynamically at runtime?

只愿长相守 提交于 2019-12-03 08:40:44

问题


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

Thanks :)


回答1:


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




回答2:


You can try something like this, but it requires you to know, where exactly your JARs are located.

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


来源:https://stackoverflow.com/questions/15204913/how-to-add-an-external-jar-file-to-the-classpath-dynamically-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!