2013-03-04 64 views

回答

11
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

+0

你真的不应该使用'#类的newInstance()',因为它可以引入一个未经宣布的检查异常http://docs.oracle.com/javase/tutorial/reflect/member/ctorTrouble.html它的更好使用'Class#getConstructor()#newInstance()' – 2013-03-04 15:41:36

+0

感谢NiKolay Kusznetov,我找到了答案int source讨论:) – 2013-03-04 15:50:00

2

你可以尝试这样的事情,但它需要你知道,究竟哪里你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"); 
相关问题