Java:访问JNI中的静态final字段

时间:2015-01-30 18:32:29

标签: java android java-native-interface android-5.0-lollipop android-runtime

有没有办法在JNI中访问静态最终字段?

public class TryMe {
    public int a = 1;
    public final int b = 2;
    public static int c = 3;
    public static final int d = 4;
}

C ++ JNI代码:

jclass cls = env->FindClass("my/package/TryMe");

jfieldID a = env->GetFieldID(cls, "a", "I"); //OK
jfieldID b = env->GetFieldID(cls, "b", "I"); //OK
jfieldID c = env->GetStaticFieldID(cls, "c", "I"); //OK
jfieldID d = env->GetStaticFieldID(cls, "d", "I"); //Error!

最后一次调用返回NULL并失败。知道为什么吗?

2 个答案:

答案 0 :(得分:2)

解答:我被proguard咬了。

我最初认为它可能是Android运行时中的一个错误,但事实并非如此。我相信proguard不知道也不关心JNI所以它决定优化“常数”。将此添加到proguard.cfg后:

keep class my.package.TryMe {
    public static final int d;
}

问题已经消失。

答案 1 :(得分:0)

使用javap -p -s TryMe后,变量d的显示方式如下:

  

...
  public static final int d;
      描述符:我
  ...

如果是这样,那么我真的没有看到它不应该起作用的原因。你在尝试这个平台?我在Arch x86_64上使用以下代码尝试了您的示例,它适用于我:

Test.java:

public class Test {
    public int a = 1;
    public final int b = 2;
    public static int c = 3;
    public static final int d = 4;
}

ctest.cpp:

#include <iostream>
#include <jni.h>

using namespace std;

int main(){
     JavaVM *jvm;
     JNIEnv *env;

    JavaVMInitArgs vm_args;
    JavaVMOption options[1];
    options[0].optionString = const_cast<char*>("-Djava.class.path=/home/fishi/Workspace/tmp/");
    vm_args.version = JNI_VERSION_1_8;
    vm_args.options = options;
    vm_args.nOptions = 1;
    vm_args.ignoreUnrecognized = JNI_FALSE;

    /* Create the Java VM */
    int res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args); 

     if (res == JNI_ERR){
         cout << "Fail: Unable to load JVM \t Exit" << endl;
        return 1;
     }
         else if (res == JNI_OK){
         cout << "CreateVM:\t\tJVM loaded successfully!" << endl;
     }

    /* Find class and static field */
    jclass cls = env->FindClass("Test");
    if(cls == NULL)
    {
        cout << "FindClass:\t\tCould not load class!" << endl;
        return 1;
    }
    else
    {
        cout << "FindClass:\t\tLoaded class successfully!" << endl;
    }
    jfieldID field = env->GetStaticFieldID(cls, "d", "I");
    if(field == NULL)
    {
        cout << "GetField:\t\tError!" << endl;
        return 1;
    }

    cout << "Success" << endl;
}

生成文件:

build-jni:
    g++ -g -I/usr/lib/jvm/java-8-openjdk/include/ -I/usr/lib/jvm/java-8-openjdk/include/linux/ -L/usr/bin/java -L/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/ ctest.cpp -ljvm -o ctest

run-jni:
    LD_LIBRARY_PATH=/usr/bin/java:/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/ ./ctest

输出:

  

$ make run-jni
  LD_LIBRARY_PATH = / usr / bin / java:/ usr / lib / jvm / java-8-openjdk / jre / lib / amd64 / server / ./ctest
  CreateVM:JVM成功加载!
  FindClass:已成功加载类!
  成功

希望这在某些方面有所帮助。