I have another problem that the answer eludes me. I want to take a class from an external jar at runtime and extract a method from it and pass a parameter to it. My code below currently opens the jar and grabs the class and runs the method, but when I try to pass it to the parameter, the method starts, but I get an InvocationTargetException. Any ideas?
Here is my code:
String path = "test.jar"; URL[] classes = {new File(path).toURI().toURL()}; URLClassLoader child = new URLClassLoader (classes, this.getClass().getClassLoader()); try { Class classToLoad = Class.forName("testClass", true, child); Method method = classToLoad.getDeclaredMethod ("testMethod", String.class); Object instance = classToLoad.newInstance(); Object result = method.invoke(instance, new String("Test from method!")); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }
And here is this error:
Test from method! java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at Load.loadJar(LoadTerrem.java:33) at Load.<init>(LoadTerrem.java:18) at Load.main(LoadTerrem.java:13) Caused by: java.lang.NullPointerException at MenuSingleplayer.LoadWorlds(MenuSingleplayer.java:210) at MenuSingleplayer.setup(MenuSingleplayer.java:89) at M0.LoadGame(M0.java:76) ... 7 more
As you can see, the method is executed by printing the string passed to it, but then gives an error in the string:
Object result = method.invoke(instance, new String("Test from LoadTerrem!"));
Any ideas? Thanks!
source share