2013-03-04 8 views

Odpowiedz

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

Źródło: https://stackoverflow.com/a/60775/1360074

+0

Nie należy naprawdę użyć 'NrKlasy newInstance()', ponieważ może wprowadzić nierejestrowanej sprawdzony wyjątek http://docs.oracle.com/javase/tutorial/reflect/member/ctorTrouble.html to lepiej używać 'Klasa # getConstructor() # newInstance()' –

+0

Dziękujemy NiKolay Kusznetov, Znalazłem odpowiedź int Dyskusja źródłowa :) –

2

Można spróbować coś takiego, ale wymaga, aby wiedzieć, gdzie dokładnie swoją JARs znajdują.

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