Search code examples
javarjava-native-interface

Convert Java Collection<Integer> type to R object using JNI


I have a java method which returns collection<"Integer"> and I want to use it in R. The java method is as

public Collection<Integer> search( ){ ....}

Using JNI, What should be the type of this (Java collection) object in R. I tried with "[I" , which means an integer array, but it did not worked.


Solution

  • Collection<Integer> is a type created by parameterizing the generic interface Collection, which allows some compile-time sanity checks to be performed on your usage of the Collection<Integer>.

    However, at runtime, what remains of the Collection<Integer> is just the raw type Collection. So if you're trying to find the appropriate class with FindClass you should look for java.util.Collection, i.e. "java/util/Collection".

    Once you have a reference to the class and a reference to an instance of that class you could use the toArray method in Collection to get an ordinary array of Integer objects, if that's what you want.


    A small semi-pointless example (assuming you have a jobject intColl which is referring to your Collection<Integer>):

    // Get an array of Objects corresponding to the Collection
    jclass collClass = env->FindClass("java/util/Collection");
    jmethodID collToArray = env->GetMethodID(collClass, "toArray", "()[Ljava/lang/Object;");
    jobjectArray integerArray = (jobjectArray) env->CallObjectMethod(intColl, collToArray);
    
    // Get the first element from the array, and then extract its value as an int
    jclass integerClass = env->FindClass("java/lang/Integer");
    jmethodID intValue = env->GetMethodID(integerClass, "intValue", "()I");
    jobject firstInteger = (jobject) env->GetObjectArrayElement(integerArray, 0);
    int i = env->CallIntMethod(firstInteger, intValue);
    
    __android_log_print(ANDROID_LOG_VERBOSE, "Test", "The value of the first Integer is %d", i);
    
    env->DeleteLocalRef(firstInteger);
    env->DeleteLocalRef(integerArray);