I'm working on a standalone Java application that is already modularized using JPMS. I want to be able to dynamically load a JAR that contains a JDBC driver onto the module path without specifying the path as a command line argument. I've been exploring how to do this using ModuleFinder from the Java API. However, I also need to ensure there's a fallback option for cases where the JAR file doesn't include a module-info.class. While I'm enjoying coding this feature myself, I'm curious if anyone has written similar code or has any thoughts on best practices or libraries that might help me achieve this. Thanks in advance for any pointers!
5 Answers
Have you considered looking into OSGi? It has some pretty robust solutions for dynamically loading modules that could play nicely with your setup.
You might want to consider using the Service Loader for a simpler approach. You’ll need a suitable ClassLoader, which should work fine unless you’re running inside a servlet container. If you’re aiming to dynamically load modules without app restarts while maintaining encapsulation, going with a combination of Module Layer, Module Reader, and Module Finder could be the way to go. But beware, there are some tricky pitfalls with this approach. Alternatively, I suggest keeping most of your app as named modules and allowing the dynamic part to function as an unnamed module, similar to how web apps and OSGi operate. Just a heads up, to avoid confusion, JBoss Modules has a name that might suggest it's related to Java modules, but it isn't!
I found this GitHub repo that has an example of how to load modules dynamically. Check out this specific section in their code that sets up the ModuleFinder and ClassLoader. It outlines how to define and load modules with proper configurations. It might give you a solid starting point!
Is your JDBC driver really an unnamed module, or does it define an "Automatic Module Name"? The ModuleFinder can help debug and inspect all modules in a given path, which might help clarify your situation regarding the driver.
Have you checked out Layrry? It’s worth a look for your situation, but I can't vouch for whether it will solve your specific problem. It might give you some valuable insights though!
Yeah, JBoss Modules can be a bit misleading! The naming really doesn’t reflect its purpose in the Java ecosystem.