简体   繁体   中英

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;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM