Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Java enum field from JNI?

How do I set Java enum field from JNI ? Here is the sample code. I would like to set "myState" field of my B object in the native function "get_state".

public class A {

    public enum STATE { 
        STATE_ONE,
        STATE_TWO
    }

    public static class B {
        public STATE myState;
    }

    public native void get_state(B b);

    public B getB() {
        B b;

        // Call JNI to get the state
        get_state(b);

        return b;
    }
}


JNIEXPORT void JNICALL Java_A_get_1state(JNIEnv *env, jobject object, jobject b_object)
{
    /* Get a reference to obj's class */
    jclass cls = (*env)->GetObjectClass(env, b_object);

    //How do I set B object's "myState" field?

}
like image 809
user2956951 Avatar asked Nov 05 '13 16:11

user2956951


1 Answers

Since it is a nested enum class, STATE is implicitly static. There are numerous resources, but a Google search that says exactly this can be found here: http://www.javapractices.com/topic/TopicAction.do?Id=1

This allows for another approach on top of valueOF methodID from enum class. You can use env->GetStaticField and env->GetStaticObjectField to get the enum to set.

Ex:

jclass theStateClass = env->FindClass("your/containingPackage/A$STATE");
jfieldID stateOneField    = env->GetStaticFieldID(theStateClass, "STATE_ONE", "Lyour/containingPackage/A$STATE;");
jobject STATE_ONE = env->GetStaticObjectField(theStateClass, stateOneField);
like image 199
blkhatpersian Avatar answered Oct 26 '22 23:10

blkhatpersian