我不知道这是否符合您的性能要求,但这可能是一个好的开始。
对于这两个选项,假设jobject jList;
是你的ArrayList。
Option 1
将 List 转换为数组并迭代该数组(如果您有 LinkedList 而不是 ArrayList,可能更适用)
// retrieve the java.util.List interface class
jclass cList = env->FindClass("java/util/List");
// retrieve the toArray method and invoke it
jmethodID mToArray = env->GetMethodID(cList, "toArray", "()[Ljava/lang/Object;");
if(mToArray == NULL)
return -1;
jobjectArray array = (jobjectArray)env->CallObjectMethod(jList, mToArray);
// now create the string array
std::string* sArray = new std::string[env->GetArrayLength(array)];
for(int i=0;i<env->GetArrayLength(array);i++) {
// retrieve the chars of the entry strings and assign them to the array!
jstring strObj = (jstring)env->GetObjectArrayElement(array, i);
const char * chr = env->GetStringUTFChars(strObj, NULL);
sArray[i].append(chr);
env->ReleaseStringUTFChars(strObj, chr);
}
// just print the array to std::cout
for(int i=0;i<env->GetArrayLength(array);i++) {
std::cout << sArray[i] << std::endl;
}
Option 2
另一种选择是使用List.size()
and List.get(int)
方法从列表中检索数据。当您使用 ArrayList 时,此解决方案也可以,因为 ArrayList 是 RandomAccessList。
// retrieve the java.util.List interface class
jclass cList = env->FindClass("java/util/List");
// retrieve the size and the get method
jmethodID mSize = env->GetMethodID(cList, "size", "()I");
jmethodID mGet = env->GetMethodID(cList, "get", "(I)Ljava/lang/Object;");
if(mSize == NULL || mGet == NULL)
return -1;
// get the size of the list
jint size = env->CallIntMethod(jList, mSize);
std::vector<std::string> sVector;
// walk through and fill the vector
for(jint i=0;i<size;i++) {
jstring strObj = (jstring)env->CallObjectMethod(jList, mGet, i);
const char * chr = env->GetStringUTFChars(strObj, NULL);
sVector.push_back(chr);
env->ReleaseStringUTFChars(strObj, chr);
}
// print the vector
for(int i=0;i<sVector.size();i++) {
std::cout << sVector[i] << std::endl;
}
_编辑:用 NULL_ 替换 JNI_FALSE
_编辑:用push_back_替换插入