Search code examples
androidandroid-ndkjava-native-interface

JNI Casting jobject from one class to another


So if I had a jobject from jclass clazz1 and I wanted to type cast it to jclass clazz2. How would would go about doing that?

I check Oracle JNI docs and the only reference to casting is from the function IsAssignableFrom() but not much more.


Solution

  • A jobject represents a reference to some Java object, but the Java type of that object is not important. You can always assign one jobject to another jobject.

    However, the Java type does matter once you try to actually use the object for anything, like calling one of its methods or accessing one of its fields.

    At that point you should ensure that the object you're providing meets the following requirements:

    • The object's class is exactly the same as the expected class, OR
    • The object's class is a subclass of the expected class, OR
    • The object's class implements the expected class' interface.

    That's precisely what IsAssignableFrom will tell you.

    If your clazz1 object meets these requirements you can use it in your C++ code as if it were a clazz2.