user1989504
user1989504

Reputation: 143

JNI call to find Java class from native results in NoCLassDefFoundError

I am using following code to access a java class from native code

JNIEnv *env = nullptr;

JMVEnv::attachCurrentJNIENv(&env);

jclass jXYZClass = env->FindClass("com/xxx/xx/xx/XYZClassName");

This call passes 4-5 times but fails after that. jXYZClass is null after some calls.

So, while compilation class is found and during execution also it was found 4-5 times. I am calling this code from different locations. Can it be some threading issue?

Upvotes: 1

Views: 626

Answers (1)

kaitian521
kaitian521

Reputation: 578

I think it is a multhreading problems... Especially when you say that " it was found 4-5 times. I am calling this code from different locations".

See this post for more details.

Firstly, you can print the thread id of each thread to see if they are the same thread.

You can Findclass in JNI_OnLoad:

jobject g_class;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *pjvm, void *reserved) {
    JavaVM *gJvm = pjvm;  // cache the JavaVM pointer
    JNIEnv *env= NULL;
    env = gJvm->GetEnv((void**)&env, JNI_VERSION_1_6);
    jclass tmp = env->FindClass("com/xxx/xx/xx/XYZClassName");
    g_class = env->NewGlobalRef(tmp);
}

whenever you want to use this class:

// extern jobject g_class; Add this Line if this is in another cpp file
jmethodID methodID = env->GetMethodID((jclass)g_class, "<init>", "()V");
jobject new_object = env->NewObject((jclass)g_class, methodID);

Upvotes: 2

Related Questions