java 如何从 JNI 返回枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11225261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:18:10  来源:igfitidea点击:

how to return enum from JNI

javaenumsjava-native-interface

提问by krt

In java I have:

在java中我有:

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.

我希望本机方法 'nativeGetStatus' 返回此枚举值。

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?

JNI 返回整数并与 java 中的枚举值进行比较是一个选项,但想知道是否可以通过 jobject 返回值并将其直接分配给 state ?如果是,如何?

采纳答案by Vladimir Ivanov

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

当然,你可以做到。Enum 值是 Enum 类的公共静态字段,因此您可以使用官方手册编写代码。只需从 JNI 获取字段并将其作为作业返回。

回答by cweigel

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):

我为接受的答案苦苦挣扎,因为我有一段时间无法弄清楚静态字段的签名。所以这是应该与上面的例子一起工作的 JNI 实现(未经测试):

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

return STATUS_ONE;