javajava-native-interfacejava-9java-modulejnienv

Module path in C++ to Java JNI Call


When I create a Java 8 JVM in C++ I usually use something like the following code to tell JVM the class path:

JavaVMOption* options = new JavaVMOption[1];   // JVM invocation options
options[0].optionString = (char *)"-Djava.class.path=.;./lib2";   // where to find java .class
vm_args.version = JNI_VERSION_1.8;             // minimum Java version
vm_args.nOptions = 1;                          // number of options
vm_args.options = options;
vm_args.ignoreUnrecognized = false;

But how to tell the Java 9 JVM about the module path? There is no java.module.path system property. The best I can find is something like:

JavaVMOption* options = new JavaVMOption[2];   // JVM invocation options
options[0].optionString = (char *)"-Djdk.module.path=.;./lib2";   // where to find java .class
options[1].optionString = (char *)"-Djdk.module.main=RemkaAgentService";   // where to find java .class
vm_args.version = JNI_VERSION_9;             // minimum Java version
vm_args.nOptions = 2;                          // number of options
vm_args.options = options;
vm_args.ignoreUnrecognized = false;

But this code does not work, it fails when I try to create JVM. I suppose it is because it does not support the options I try.


Solution

  • This is a late answer but persons that make searches about this problem may find it useful. There is indeed very few documentation to address this case, which is unfortunate. I spent some time to investigate this problem and I found a way to make it work. Here are the steps to take.

    The first step removes the requirement to define the '--module-path' flag that is not supported by JNI. Note that to properly bundle your application, all you jars must be converted to modular jars. Third-party jars may not be true modular jars but rather automatic modules, but automatic modules are not supported by jlink (Using jlink with automatic modules). Fortunately, there is a method to perform this automatically documented here : creating module-info for automatic modules with jdeps in java 9

    The second step works even if your class lies within a module. Notes that the class name parameter for a class 'p1.p2.p3.MyClass' must be 'p1/p2/p3/MyClass'. I mentioned this as I wasted some time due to this difference in the convention.

    I may publish an example if I can find some time for this but it may not happens in a short time-frame.