JNI(Java Native Interface)使Java拥有了和其他语言进行通信的能力。Java中声明为native的方法会被编译为本地代码,例如C/C++、Object C等待,以提高代码执行的效率。
手工编译具有native类的方法如下:
- 将需要调用JNI的方法声明为native方法。如
public final class Array {
private Array() {}
public static native int getLength(Object array);
public static native Object get(Object array, int index);
}
- 将.java源文件编译为.class文件。
- 在此目录下,使用命令行 javah -jni Array 将.class文件编译为.h文件,例如:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Array */
#ifndef _Included_Array
#define _Included_Array
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Array
* Method: getLength
* Signature: (Ljava/lang/Object;)I
*/
JNIEXPORT jint JNICALL Java_Array_getLength
(JNIEnv *, jclass, jobject);
/*
* Class: Array
* Method: get
* Signature: (Ljava/lang/Object;I)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_Array_get
(JNIEnv *, jclass, jobject, jint);
#ifdef __cplusplus
}
#endif
#endif
- .h文件编译为.dll动态库文件。
- java中可以使用System.loadLibrary方法对.dll加载。
参考: