How to convert Java Object types like Long and Integer to primitive types like long and int

My Java method signature is as follows :

public native Long passLong(MyEntity myEntity);  

Then maps :

extern "C"
JNIEXPORT jobject JNICALL
Java_passLong(JNIEnv *env, jobject instance, jobject myEntity) {

    jclass myEntityClazz = env->GetObjectClass(myEntity);
    jmethodID get_myEntityGUID = env->GetMethodID(myEntityClazz, "get_myEntityGUID", "()Ljava/lang/Long;");
    jobject myEntityGUID = env->CallObjectMethod(myEntity, get_myEntityGUID);

    // Convert the Long object to a primitive here

    return myEntityGUID;

}  

How can I go about converting a Java Long Object to a C primitive?

Thank you all in advance.

MyEntity

public class MyEntity {

    private Long _myEntityGUID;

    public Long get_myEntityGUID() {
        return _myEntityGUID;
    }

    public void set_myEntityGUID(Long _myEntityGUID) {
        this._myEntityGUID = _myEntityGUID;
    }
}

1 answer

  • answered 2018-05-16 04:42 John Bollinger

    How can I go about converting a Java Long Object to a C primitive?

    Invoke its longValue() method. Beware that you need to test first whether the object is null, or else be prepared to handle a NullPointerException (just as when using auto(un)boxing on the Java side).

    Note, too, that where possible, it is much easier to handle things like this on the Java side than in JNI. That does not appear to be possible in the example you present, but perhaps you could refactor so that the native method does less, and therefore does not need a whole MyEntity as an argument.