JNI- FindClass returns null

10,255

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.

Share:
10,255
merveotesi
Author by

merveotesi

A violet boson

Updated on June 04, 2022

Comments

  • merveotesi
    merveotesi almost 2 years

    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