4

有没有办法访问 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 并失败。知道为什么吗?

4

2 回答 2

2

已解决:我被proguard咬了。

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

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

问题消失了。

于 2015-02-02T12:28:32.713 回答
0

使用后javap -p -s TryMe,变量是否d如下所示:

...
公共静态最终 int d;
描述:我
...

?

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

测试.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: 加载类成功!
成功

希望这在某种程度上有所帮助。

于 2015-01-30T20:22:50.623 回答