title: Java loading an external class in runtime
body: <p>I have yet another issue which the answer is eluding me.  I wish to take a class from an external jar at runtime and grab a method from it and pass it a parameter.  My code below currently opens the jar and grabs the class and runs the method but when I try and pass it a parameter, the method runs but I get an InvocationTargetException.  Any ideas?</p>
  
  <p>Here is my code:</p>
  
  <pre><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();
      }
  </code></pre>
  
  <p>And here is the error it throws:</p>
  
  <pre><code>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.&lt;init&gt;(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
  </code></pre>
  
  <p>As you can see, the method executes, printing out the string passed to it but then throws an error on the line: </p>
  
  <pre><code>Object result = method.invoke(instance, new String("Test from LoadTerrem!"));
  </code></pre>
  
  <p>Any ideas? Thanks!</p>