How to load .jar file in C ++ using JNI

I am trying to load a method present in the .jar. Below is the code snippet

JavaVMInitArgs vm_args;
memset(&vm_args, 0, sizeof(vm_args));
JavaVMOption* options = new JavaVMOption[1];

options[0].optionString =
      "-  Djava.class.path=C:\\Users\\Desktop\\POC\\POC\\Debug\\Sample2.jar;    
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = 0;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
m_Status = JNI_CreateJavaVM_ptr (&m_JVM, (void**)&m_JavaEnv, &vm_args);

      

But when I use

     classForJava = m_JavaEnv->FindClass ("Sample2");

      

classForJava

contains 0

.

+1


source to share


2 answers


In Java, there are only two ways to make Java look in a .jar file and specify the .jar file in the classpath, or create a classloader that looks like in that jar file and add it to the list of Java class loaders.

And of course, the whole classpath is a collection of classloaders that Java creates and uses before your program even starts.



Thus, the JNI program has to force Java calls to create a new classloader and force Java to start using it if the JNI program needs Java to look in additional .ar files.

+4


source


Specify the fully qualified class name, including the package name .

, replaced with /

. For example, if your class Sample2

is in a package org.test

usem_JavaEnv->FindClass ("org/test/Sample2");



By the way, it might be a typo, but the space optionString

between -

and Djava.class.path

should be removed.

0


source







All Articles