What is the Java 9 reflection equivalent of --add-modules?
Asked Answered
D

1

8

I need a way to tell a newly created class loader (with no set parent) about modules I want exposed to it (e.g. java.scripting).

What's the reflection equivalent of passing --add-modules on the command line?

Daphnedaphnis answered 7/6, 2017 at 5:1 Comment(2)
AFAIK, that would be --add-opens, e.g. --add-opens java.base/java.util=ALL-UNNAMEDProchora
@Stefan Zobel that's also a command line flag, no? I need a programatic way.Daphnedaphnis
I
6

There is no programmatic way to substantially edit the module graph created by the JVM on launch (adding reads edges is the only exception). This was a deliberate decision to keep the running application secure and stable. (Case in point, what would happen to your code, if you ran on a runtime that doesn't contain the java.scripting module?)

What you can do, though, is create a new layer, which contains an entirely new module graph. When launching the JVM, it will create a single layer from the command line flags and the module path content. With the existing API, you can then create new layers on top of that one. To learn about layers, have a look at The State of the Module System and the Javadoc for ModuleLayer.

Irreligion answered 7/6, 2017 at 14:11 Comment(2)
The weird thing is that even if I pass --add-modules=java.scripting when I start the app java.scripting classes fail to be looked-up by classes loaded through my new ClassLoader object. Isn't exposed modules inherited between the default and new class loaders?Daphnedaphnis
The classes in the java.scripting module are defined to the platform class loader. What is the parent of the custom class loader? If it delegates to the system class loader then it will find the javax.scripting.* classes. If it delegates to the boot loader (null) then it is out of luck (no guarantee that all system classes are visible to the boot loader).Epilimnion

© 2022 - 2024 — McMap. All rights reserved.