3

Our Java-based application has a tiny "bootloader.jar" and the core application jars. The core application jars might be loaded either from the default (file system) location or from another where a previous application run might have downloaded updated jars. The bootloader runs following code:

final List<File> jars = getJarsToAddToClasspath();
final String mainClassName = getMainClassName();

final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
final Class<?> mainClass = urlClassLoader.loadClass(mainClassName);
final Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
mainMethod.invoke(null, new Object[] {args});

According to http://www.oracle.com/technetwork/java/javase/9-relnote-issues-3704069.html it looks like this won't work any more with Java 9:

Note that Java SE and the JDK do not provide an API for applications or libraries to dynamically augment the class path at run-time.

Could someone confirm this?

Thomas S.
  • 5,804
  • 5
  • 37
  • 72
  • Adding a directory to the static class path? `"lib/*"` – Joop Eggen Jan 04 '18 at 10:59
  • This location is not known before launching the bootloader code. The directory may contain also older versions of the jars, so we need to just add the dedicated ones in the right order to the classpath. – Thomas S. Jan 04 '18 at 11:05
  • 2
    The code sample in the question creates a URLClassLoader, it's not attempting to dynamically extend the application class path. So I don't think you will have an issue. Try it out :-) – Alan Bateman Jan 04 '18 at 11:35
  • @AlanBateman: Yes, it seems to work, but what else than "extending the class path dynamically" is loading classes from arbitrary .jar files configured at run-time? – Thomas S. Jan 05 '18 at 13:57
  • This question is no duplicate, because my posted code does not assume anything on the parent class loader. Hence it does NOT crash on Java 9. – Thomas S. Jan 06 '18 at 12:06

1 Answers1

2

I think it should still work. The simplest way to know is to try it. From the same Oracle page:

Code that assumes that ClassLoader::getSytemClassLoader returns a URLClassLoader object will need to be updated.

Your code does not rely on the system classloader being of type URLClassloader. All it does is set it as the delegated parent of the custom classloader. This custom classloader will delegate to it to search for classes and resources regardless of its implementation.

M A
  • 71,713
  • 13
  • 134
  • 174