Java loads an external class at runtime

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!

+2
source share
2 answers

InvocationTargetException is testMethod when the called method ( testMethod in your case) throws an exception. From the docs:

InvocationTargetException - A thrown exception that wraps an exception thrown by the called method or constructor.

Judging by your stack trace ("because of" part, to be precise), it looks like testMethod calls MenuSingleplayer.LoadWorlds , which raises a NullPointerException . This NullPointerException until it reaches the reflexive call, after which it is wrapped in an InvocationTargetException .

+3
source

The problem is the MenuSingleplayer.LoadWorlds method. It says NPE happened there. It has nothing to do with thinking. This is normal:

 Caused by: java.lang.NullPointerException at MenuSingleplayer.LoadWorlds(MenuSingleplayer.java:210) 
+3
source

Source: https://habr.com/ru/post/1203835/


All Articles