使用后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: 加载类成功!
成功
希望这在某种程度上有所帮助。