I am creating a URLClassloader to load some jars. Each jar gets loaded correctly from a different classloader and each jar contains a class with a method run(). Now the body of this run() can create an anonymous inner class in it. However, because i created my URLClassloader in a try-with-resources block it gets autoclosed and at run time when it tries to load the anonymous inner class it throws a NoClassDefFoundError because the classloader is already closed.
Now my question is, what is the normal practice for these situations? is it ok to leave the classloader open so that when later it needs to load something else, it can? is there a way to reopen a closed classloader?
If I leave the classloader open, the compiler gives me warnings about potential resource leaks so I have a feeling this is like streams where you are not supposed to leave them open indefinitely. However because of the nature of classloaders, if it's not the same classloader that loads the anonymous class, it cannot be used in the outer class
here is the code where the classloader is created
public Player(File codePath) throws PlayerException {
try (URLClassLoader loader = new URLClassLoader(new URL[] { codePath.toURI().toURL() })) {
//load class from Jar where run() method creates anonymous class that comes in the jar too
} catch (ClassCastException | IOException | ClassNotFoundException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException
| SecurityException exc) {
throw new PlayerException("Error loading player's code", exc);
}