XTT XTT - 22 days ago 8
C Question

Creating an Integer Object in JNI

I want an Integer object to be return to the java layer from the JNI. The following code crashes when calling

NewObject(env, interger, init, rc)
. What is the proper way to create a Integer object and return it?

jint rc = 0;

jclass intClass = (*env)->FindClass(env, "java/lang/Integer");
if (intClass == NULL) {
return NULL;
}
jmethodID init = (*env)->GetMethodID(env, intClass, "intValue", "()I");
if (init == NULL) {
return NULL;
}
jobject rc_obj = (*env)->NewObject(env, intClass, init, rc);
if (rc_obj == NULL) {
return NULL;
}

return rc_obj;


Thanks!

Answer

Try this:

jclass cls = (*env)->FindClass(env, "java/lang/Integer");
jmethodID midInit = (*env)->GetMethodID(env, cls, "<init>", "(I)V");
if (NULL == midInit) return NULL;
jobject newObj = (*env)->NewObject(env, cls, midInit, number);