Receive in C++ a Java generic object as a method return type using JNI

  android, c++, generics, java, java-native-interface

I have a C++ wrapper that calls Java functions of a Java SDK using JNI.

In the Java code there is a generic class, for example let’s call it MyClass, that is defined like this:

public class MyClass<T> extends HashMap<String, T> {
    ...
}

In the C++ code I am calling a Java function using JNI, for example let’s call it getMyClass, that is defined like this:

public MyClass<String> getMyClass() {
    return myclassObject;
}

So, the Java function getMyClass returns an object of type MyClass and I’d like to read this object in the C++ code where it is returned.

I tried casting the returned Java object with JNI’s parameter type jobject, but it doesn’t seem to work as it always has a null value. In other words, I tried something like this which would work if the returned object Java was of type String for example.

auto jObjectMyClass = (jobject) env->CallObjectMethod(jObjectThatHasGetMyClassFunction, getMyClassMethod);

Questions:

  1. Is there any other casting that I could try when receiving the Java object in the C++ code, in order for this to work in a similar way?
  2. Is there any other better way in which I should approach this matter of receiving a generic class object using JNI?

Source: Windows Questions C++

LEAVE A COMMENT