18
我想使用java代码动态地将jar文件添加到我的项目的类路径中,如果可能的话,我想使用外部jar文件并加载它们的类,稍后将它们作为Beans执行(Spring框架)。如何在运行时动态地将外部jar文件添加到ClassPath中?
谢谢:)
我想使用java代码动态地将jar文件添加到我的项目的类路径中,如果可能的话,我想使用外部jar文件并加载它们的类,稍后将它们作为Beans执行(Spring框架)。如何在运行时动态地将外部jar文件添加到ClassPath中?
谢谢:)
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);
你可以尝试这样的事情,但它需要你知道,究竟哪里你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");
你真的不应该使用'#类的newInstance()',因为它可以引入一个未经宣布的检查异常http://docs.oracle.com/javase/tutorial/reflect/member/ctorTrouble.html它的更好使用'Class#getConstructor()#newInstance()' – 2013-03-04 15:41:36
感谢NiKolay Kusznetov,我找到了答案int source讨论:) – 2013-03-04 15:50:00