0

I have a problem loading class from JAR file.

I can load them with URLClassLoader using a JarFile etc etc like in this answer; but if later in code I try to instantiate them with reflection:

Object obj = Class.forName(className).newInstance()

I get a ClassNotFoundException. Can I dinamically load a class to use them later, when I need them, just like classes in ClassPath? Thank you!

Andrean
  • 313
  • 1
  • 4
  • 13
  • I think you should call newInstance() on the Class instance you already loaded with the code you are referencing or make sure the jar file is on the classpath – Juan May 19 '18 at 13:19
  • It seems to be a class path issue. The exception is likely coming from the forName call. Are you sure the class you are trying to instantiate is in the class path? – whbogado May 19 '18 at 13:53
  • Class i'm trying to instantiate is not in classpath, it is in an external jar file – Andrean May 19 '18 at 16:28

1 Answers1

0

You need to provide class loader to Class.forName method - as otherwise it will look in this same class loader as your class is in.
Object obj = Class.forName("name", true, loader).newInstance() .

But you can't just load a class and then use it in your code like MyLoadedType - as here java does not know where to look for that class, unless you will ensure that your code and loaded code is in this same class loader - you can do this by running all your code from custom class loader that allows for adding new sources in runtime. (URLClassLoader allows for this but method is protected - so you need to extend it and make it public, in java 8 system class loader is also URLClassLoader - but this was changed in java 9) .

But you can operate on that code using reflections like I showed you.

GotoFinal
  • 3,585
  • 2
  • 18
  • 33