Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI FindClass can't find class which uses jar

I'm working on a project where some Java functions must be called from C++ code using JNI. I've tried that with a simple Java class, but when I'm starting to use extra .jar in my Java project JNI's FindClass function can't find my class. I've done some research and read about classpath which is needed for compiling .java file if it uses extra libs, but FindClass returns null in that case. Here's basic structure of my code

JavaVMOption options[2];
JNIEnv *env;
JavaVM *jvm;
JavaVMInitArgs vm_args;
long status;
jclass cls;
jmethodID mid;
jint square;
jboolean not;

options[0].optionString = "-Djava.class.path=<path_to_my_java_class>";
options[1].optionString = "-Djava.library.path=<path_to_my_jar_file>";
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 2;
vm_args.options = options;
status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

if (status != JNI_ERR)
{
    cls = env->FindClass("package/ClassName"); //returns null while using jar
    if(cls != 0)
    {   
        //do some stuff
    }
    jvm->DestroyJavaVM();
    return 0;
}
else
    return -1;

Any ideas?

UPDATED: I've also tried

options[0].optionString = "-Djava.class.path=<path_to_my_java_class>;<path_to_jar>";

    options[0].optionString = "-Djava.class.path=<path_to_my_java_class>";
    options[1].optionString = "-classpath <path_to_jar>";
like image 936
nabroyan Avatar asked Jul 31 '13 13:07

nabroyan


2 Answers

I think that your mistake is that you are putting a JAR on the "library.path". The library path is the path for finding native libraries ... not JAR files.

You should put the JAR file on the classpath; e.g.

    options[0].optionString = 
        "-Djava.class.path=<path_to_my_java_class>:<path_to_my_jar_file>";

(On Windows, use ";" as the classpath separator instead of ":".)

like image 97
Stephen C Avatar answered Oct 21 '22 23:10

Stephen C


I figured out, that there were 2 problems

1) path_to_my_jar_file

This path must point to the jar file and not to the directory folder which contains it.

2) -Djava.library.path

Comments of Drew McGowen and answer of Stephen C were right - path to jar file must be like they said.

like image 31
nabroyan Avatar answered Oct 21 '22 23:10

nabroyan