foreword
Today, I was looking at the HashMap source code, and then I clicked on the Object class. I saw several native identification methods. If I don't understand it, I will first popularize the native method. I will get it first, and I will add the analysis of HashMap tomorrow.
native methods are called native methods. It is declared with the keyword "native" in the java source program and does not provide a function body. Its implementation is written in another file using C/C++ language, and the written rules follow the Java native Interface (JNI) specification of the Java native interface. In short, it is a callable method implemented in C/C++ declared in Java.
Implementation
Write a java class with methods declared by natives
Not much to say, the code is as follows
package local.zcw.demo; /** * 作者 zcw * 时间 2017/10/24 18:04 * 版本 1.0.0 * 描述 TODO */ public class MyNative { static { System.loadLibrary("MyNative"); } public static native void sayHello(); public static void main(String[] args) { MyNative.sayHello(); } }
Compile java classes using javac command
cd src/ javac local/zcw/demo/MyNative.java
Use the javah -jni command to generate *.h header files
javah -jni local.zcw.demo.MyNative
The content of the generated file is as follows
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class local_zcw_demo_MyNative */ #ifndef _Included_local_zcw_demo_MyNative #define _Included_local_zcw_demo_MyNative #ifdef __cplusplus extern "C" { #endif /* * Class: local_zcw_demo_MyNative * Method: sayHello * Signature: ()V */ JNIEXPORT void JNICALL Java_local_zcw_demo_MyNative_sayHello (JNIEnv *, jclass); #ifdef __cplusplus } #endif #endif
Implement native methods using c language
#include "jni.h" #include "local_zcw_demo_MyNative.h" #include <stdio.h> JNIEXPORT void JNICALL Java_local_zcw_demo_MyNative_sayHello(JNIEnv * env, jclass obj) { printf("hello by c\n"); }
Generate a dynamic link library from files written by native methods
gcc -dynamiclib -I ${JAVA_HOME}/include/ \ -I ${JAVA_HOME}/include/darwin/ \ local_zcw_demo_MyNative.c \ -o libMyNative.jnilib
run
java local.zcw.demo.MyNative
other
The project directory is as shown below, the code download
The complete command is as follows
Reference article
Supplement (using jni under Linux 2017/12/19)
Compile dynamic library under linux
gcc -I ${JAVA_HOME}/include -I ${JAVA_HOME}/include/linux \ -fPIC -shared -o libMyNative.so \ local_zcw_demo_MyNative.c
run
direct execution
java local.zcw.demo.MyNative
throw java.lang.UnsatisfiedLinkError exception
Shared library path can be specified
java -Djava.library.path='.' local.zcw.demo.MyNative
or add environment variable
export LD_LIBRARY_PATH="libMyNative.so路径":$LD_LIBRARY_PATH