how to create Class[] in JNI

时间:2017-03-01 11:46:06

标签: java java-native-interface

I have to pass a Class[] from jni to java. I create the array in my native code as below,

array = (*env)->NewObjectArray(env, 10, (*env)->FindClass(env, "java/lang/Class"), NULL);

I need to insert, Integer[].class and Integer.TYPE into this array and receive it in my java program.

public int Sample(Class[] cls){
   //some code
}

How can I insert the elements into the array in my jni layer using SetObjectArrayElement().

1 个答案:

答案 0 :(得分:0)

像这样(我使用更紧凑的C ++ JNI调用):

jclass classClass = env->FindClass("java/lang/Class");
jclass intClass = env->FindClass("java/lang/Integer");
jclass intArrayClass = env->FindClass("[java/lang/Integer";
jfieldID fid = env->GetFieldID(intClass, "TYPE");
jclass intTypeClass = (jclass)env->GetStaticObjectField(intClass, fid);
jobjectArray array = env->NewObjectArray(2, classClass, 0);
env->SetObjectArrayElement(array, 0, intTypeClass);
env->SetObjectArrayElement(array, 1, intArrayClass);

请注意,根据此数组的使用方式,您可能需要将数组及其元素从本地引用转换为全局引用。