JVM cannot find class when using JNI from C ++
I am trying to call JAVA methods from C ++ JNI. First of all I got this example, tried it. I changed the JDK path and after that I could run the examples and they worked correctly.
After that I tried to import my own JAR file and use one class from it. I copied the code from the example and replaced the classpath and classname with my own:
void MyCPPClass::CallJava()
{
JavaVM *jvm; // Pointer to the JVM (Java Virtual Machine)
JNIEnv *env; // Pointer to native interface
//==================== prepare loading of Java VM ============================
JavaVMInitArgs vm_args; // Initialization arguments
JavaVMOption* options = new JavaVMOption[ 1 ]; // JVM invocation options
options[ 0 ].optionString = "-Djava.class.path=MyJar.jar"; // 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; // invalid options make the JVM init fail
//================= load and initialize Java VM and JNI interface ===============
jint rc = JNI_CreateJavaVM( &jvm, (void**)&env, &vm_args ); // YES !!
delete options; // we then no longer need the initialisation options.
//========================= analyse errors if any ==============================
// if process interuped before error is returned, it because jvm.dll can't be
// found, i.e. its directory is not in the PATH.
if( rc != JNI_OK )
{
exit( EXIT_FAILURE );
}
jclass cls1 = env->FindClass( "aaa/bbb/MyClass" );
...
}
JAR contains only one class aaa.bbb.MyClass
and is executed with IntelliJ IDEA command and mvn package
. I copied the JAR file next to my executable.
The value is rc
always 0 ( JNI_OK
), but the value is cls1
always NULL
. I think the JVM can find the JAR, because when I debug, I cannot remove the JAR after FindClass
.
The JAR file contains the MyClass.class file, I checked it out.
I checked several previous questions ( 1 , 2 , 3 and some others), but I couldn't figure out where I went wrong.
UPDATE: I tried to copy the MyClass.class file and MyJar.jar file to the directory of the example linked earlier and the JVM cannot find it MyClass
. Perhaps there is something missing from my java source file? The package declaration is correct.
What could be causing the JVM to fail to find MyClass
?
source to share