我有以下几个类:
NativeClass.java
public class NativeClass {
public static final int CONSTANT_VALUE = getValue();
public static native int getValue();
}TestClass.java
public class TestClass {
public static void main(String[] args) {
System.loadLibrary("native");
System.out.println(NativeClass.CONSTANT_VALUE);
}
}C代码:
#include <jni.h>
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
(*env)->FindClass(env, "LNativeClass;");
return JNI_VERSION_1_6;
}
JNIEXPORT jint JNICALL Java_NativeClass_getValue(JNIEnv *env, jclass cls) {
return 5;
}我像这样编译了C文件:
gcc NativeClass.c -I"JNI_HEADER_PATH" -shared -fPIC -o libnative.so并像这样执行代码:
java -Djava.library.path=. TestClass然后,我得到了以下异常:
Exception in thread "main" java.lang.UnsatisfiedLinkError: NativeClass.getValue()I如果我将System.loadLibrary("native");移到NativeClass中的静态初始化程序块中,它就能正常工作:
public class NativeClass {
static {
System.loadLibrary("native");
}
public static final int CONSTANT_VALUE = getValue();
public static native int getValue();
}这里我漏掉了什么?这里的代码只是我在项目中遇到的错误的一个例子。我绝对需要在NativeClass中声明常量,还需要在JNI_OnLoad中找到该类,因为我必须在其中调用静态方法。
发布于 2015-10-30 18:01:41
main是TestClass的一部分,在加载TestClass之前无法调用。但在调用System.loadLibrary("native");之前,无法加载TestClass。
所以这就是
public static void main(String[] args) {
System.loadLibrary("native");永远不能被调用-调用main依赖于被加载的类,而被加载的类依赖于被调用的loadLibrary,而被调用的main又依赖于被调用的main……
https://stackoverflow.com/questions/33427845
复制相似问题