22

In java I have:

public class MyClass{

    public enum STATUS {
        ZERO,
        ONE ,
        TWO
    }

    public native STATUS nativeGetStatus();

    ...

    private STATUS state = nativeGetStatus(); //returns enum
    private STATUS state2 = nativeGetStatus(); //returns enum 

}

I want native method 'nativeGetStatus' to return this enum value.

JNI returning integer and comparing with value of enum in java is an option, but was wondering is it possible to return value via jobject and assign it directly to state ? if yes how?

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
krt
  • 267
  • 1
  • 3
  • 11

2 Answers2

57

I struggled with the accepted answer since I couldn't figure out the signature of the static field for a while. So here's the JNI implementation that should work with the example above (not tested):

jclass clSTATUS    = env->FindClass("MyClass$STATUS");
jfieldID fidONE    = env->GetStaticFieldID(clSTATUS , "ONE", "LMyClass$STATUS;");
jobject STATUS_ONE = env->GetStaticObjectField(clSTATUS, fidONE);

return STATUS_ONE;
cweigel
  • 1,473
  • 16
  • 20
  • I have a class that has an internal Enum and this example helped me specify an object of the Enum type with 'LClass$InternalEnum;'. Thanks a lot! – mpellegr Aug 14 '13 at 17:46
  • 1
    Thanks! This answer helped me. Note for who is not too familar with Java&JNI like me: you have to specify class package within it's name both in FindClass and GetStaticFieldID, for example "com/example/MyClass$STATUS". – Vlad Jan 21 '16 at 11:59
-2

Of course, you can do it. Enum values are public static fields of Enum class, so you can use this official manual to write the code. Just get the field from JNI and return it as jobject.

namuol
  • 9,816
  • 6
  • 41
  • 54
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • are you pointing to access field 'state' and return it as jobject? sorry I missed to mention in my original post that there might be more than one field which would be assigned return value of nativeGetStatus. In this case " Just get the field from JNI and return it as jobject" might not work – krt Jun 27 '12 at 11:58
  • No, I mean that ONE is a static field of class STATUS. You can access it and return from JNI. – Vladimir Ivanov Jun 27 '12 at 13:09
  • 54
    [This is why you should never provide a link as an answer](http://25.media.tumblr.com/d10e5fba3bfbe874fbda2fcd8c2c2415/tumblr_mkvzqac3YX1r55vh6o1_1280.png). – namuol May 04 '13 at 02:10
  • 1
    +l for awesome tumbler link – Nicholas Wilson Mar 10 '15 at 14:29
  • @namuol, I see what you did here – Quirin F. Schroll Jun 22 '23 at 13:54