开发者

JNI- FindClass returns null

I know it is a common problem, i searched google and look at everything in first 4 pages, have tried many possibilities but no result so far.

Here is C++ code part:

JNIEnv* create_vm(JavaVM ** jvm) {

    char * str=(char *)"-Djava.class.path=.";

    JNIEnv *env;

    JavaVMInitArgs vm_args;

    JavaVMOption options;

    options.optionString = str; //Path to the java source code

    vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6

    vm_args.nOptions = 1;

    vm_args.options = &options;

    vm_args.ignoreUnrecognized = 0;



    int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);

    if(ret < 0)

        printf("\nUnable 开发者_如何学运维to Launch JVM\n");     

    return env;

}



int main(int argc, char* argv[])

{

    JNIEnv *env;

    JavaVM * jvm;

    env = create_vm(&jvm);

    if (env == NULL)

        return 1;




    jclass clsMain=NULL;
    jmethodID mid = NULL;

    //Obtaining Classes
    clsMain = env->FindClass("Main");

    //Obtaining Method IDs
    if (clsMain != NULL)
    {
        mid       = env->GetStaticMethodID(clsMain, "myMethod", "(Ljava/lang/String;)Z");
    }
    else
    {
        printf("\nUnable to find the requested class\n");    //this runs    
    }

...

I do not know how to catch exception and learn its name in JNI.

Also Main.class is in the same directory with the file has this C++ code part.


Edit:

i add these lines to find exception from Java after FindClass line:

clsMain = env->FindClass("Main");

jthrowable exc;
exc = env->ExceptionOccurred();
     if (exc) {
         jclass newExcCls;
         env->ExceptionDescribe();
         env->ExceptionClear();

     }

then it throws NoClassDefFoundException

thus i edit the JavaVMInitArgs.options

i mean i edit the:

char * str=(char *)"-Djava.class.path=.";

line to:

 char * str=(char *)"-Djava.class.path=/path/to/my/jars:/path/to/my/other/jars:."; 

now everything is fine. Thanks


NoClassDefFoundError occures when the JVM was unable to find a class at runtime and the class was yet found by the compîler at compile time.

So you're problem is probably a problem about the content of your Java code and/or the definition of your classpath. Your Java code is probably calling a class which is not available in the current directory.

What you should do is create a jar file with everything which is needed by your JNI call.


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

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


I tried methods mentioned above on my Mac and it didn't work. At last, I uncompressed my jar files and put them in my project folder, it works for me now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜