23

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

4

2 回答 2

15
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

于 2013-03-04T15:30:15.000 回答
3

您可以尝试这样的事情,但它需要您知道您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");
于 2013-03-04T15:32:08.557 回答