javajava-native-interface

Create a Java enum from the JNI


I've come across various answers along the lines of what I'm trying to do but nothing quite the same, any help appreciated...

I have a package scope java enum that I'd like to pass as arguemnt to java method but can't find a way to create it directly from the JNI. Is this possible?

Here's a skeleton of the code:

MyEnum.java

package com.a.b;
public enum MyEnum {
   VALUE1,
   VALUE2,
   VALUE3
}

MyClass.java

package com.a.b.c;
import com.a.b.MyEnum;
public class MyClass {
  public MyClass(MyEnum value) { ... }
}

Is it possible to call the MyClass constructor directly from the JNI? (I have no problem calling the constructor if I drop the enum, i.e. pass a String an have the java code do the conversion, but can't work out how to do it otherwise).


Solution

  • It's fairly straight-forward. Each enum value is a static field of type MyEnum:

    jclass myenum_clazz = env->FindClass("com/a/b/MyEnum");
    jfieldID value2_fid = env->GetStaticFieldID(myenum_clazz, "VALUE2", "Lcom/a/b/MyEnum;");
    jobject value2 = env->GetStaticObjectField(myenum_clazz, value2_fid);
    ...
    jobject myclass = env->NewObject(myclass_clazz, myclass_init, value2);