1

I would like to load a class from another JAR (imported as file during runtime) and handover an Object (this) to the Constructor of the class which should be loaded.

I tried doing that with the following code:

URLClassLoader cl2 = URLClassLoader.newInstance(new URL[] { new URL("jar:file:" + jarPath +"!/") });
Class c2 = cl2.loadClass("main.Class2BeLoaded");
Object loadedClass = c2.getConstructor(Object4Constructor.class).newInstance(this));

It seems so, that the Object which I handover to the constructor (this) can't be used from the code which runs in the JAR.

What is wrong? If I run this code in the same JAR everything works.

Daniel
  • 27
  • 4
  • 3
    Possible duplicate of [How to load Classes at runtime from a folder or JAR?](http://stackoverflow.com/questions/11016092/how-to-load-classes-at-runtime-from-a-folder-or-jar) – Roman Vottner Jul 30 '16 at 08:37
  • That question doesn't answer my question. I edited my post - now it should be clearly what I mean – Daniel Jul 30 '16 at 15:45
  • 1
    Don't use `newInstance(this)`. Instead, you need something like this: `(Test)Class.forName("Test").getConstructor(String.class).newInstance("Hello World");` Here the getConstructor asks what the constructor looks like (it wants a string) and then you call it with a string: http://stackoverflow.com/questions/712371/ – paulsm4 Jul 30 '16 at 15:46
  • With `URLClassLoader` you should always provide a parent loader: `URLClassLoader.newInstance(new URL[] {...}, getClass().getClassLoader());`. On trying to instantiate `main.Class2BeLoaded` Java will also attempt to load all dependent classes, `Object4Constructor` in your case. As the classloader of `main.Class2BeLoaded` however has no parent, it can't find the class definition for `Object4Constructor` and therefore fails initializing the dynamically loaded object. On passing `getClass().getClassLoader()` you tell `URLClassLoader` to ask its parent for class definitions it doesn't know. – Roman Vottner Jul 30 '16 at 16:10

0 Answers0