reference https://stackoverflow.com/questions/6101311/what-is-the-native-keyword-in-java-for
It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI (Java Native Interface).
Native methods were used in the past to write performance critical sections but with Java getting faster this is now less common. Native methods are currently needed when
- You need to call a library from Java that is written in other language.
- You need to access system or hardware resources that are only reachable from the other language (typically C). Actually, many system functions that interact with real computer (disk and network IO, for instance) can only do this because they call native code.
See Also
Java Native Interface Specification
http://blog.csdn.net/jiakw_1981/article/details/3073613
native method是什么
一個Native Method就是一個java調(diào)用非java代碼的接口。
在定義一個native method時,并不提供實現(xiàn)體(有些像定義一個java interface),因為其實現(xiàn)體是由非java語言在外面實現(xiàn)的。下面給了一個示例:
package java.lang;
public class Object {
......
public final native Class<?> getClass();
public native int hashCode();
protected native Object clone() throws CloneNotSupportedException;
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
......
}
為什么要使用Native Method
概要
java使用起來非常方便,然而有些層次的任務(wù)用java實現(xiàn)起來不容易,比如必須借助操作系統(tǒng)的接口,或者我們對程序的效率很在意時,問題就來了。
與java環(huán)境外交互
有時java應(yīng)用需要與java外面的環(huán)境交互。這是本地方法存在的主要原因,你可以想想java需要與一些底層系統(tǒng)如操作系統(tǒng)或某些硬件交換信息時的情況。
本地方法正是這樣一種交流機制:它為我們提供了一個非常簡潔的接口,而且我們無需去了解java應(yīng)用之外的繁瑣的細(xì)節(jié)。
與操作系統(tǒng)交互
JVM支持著java語言本身和運行時庫,它是java程序賴以生存的平臺,它由一個解釋器(解釋字節(jié)碼)和一些連接到本地代碼的庫組成。然而不管怎樣,它畢竟不是一個完整的系統(tǒng),它經(jīng)常依賴于一些底層(underneath在下面的)系統(tǒng)的支持。
這些底層系統(tǒng)常常是強大的操作系統(tǒng)。通過使用本地方法,我們得以用java實現(xiàn)了jre的與底層系統(tǒng)的交互,甚至JVM的一些部分就是用C寫的,還有,如果我們要使用一些java語言本身沒有提供封裝的操作系統(tǒng)的特性時,我們也需要使用本地方法。
實現(xiàn)步驟
可以將native方法比作Java程序同C程序的接口,其實現(xiàn)步驟:
- 在Java中聲明native()方法,然后編譯;
- 用javah產(chǎn)生一個.h文件;
- 寫一個.cpp文件實現(xiàn)native導(dǎo)出方法,其中需要包含第二步產(chǎn)生的.h文件(注意其中又包含了JDK帶的jni.h文件);
- 將第三步的.cpp文件編譯成動態(tài)鏈接庫文件;
- 在Java中用System.loadLibrary()方法加載第四步產(chǎn)生的動態(tài)鏈接庫文件,這個native()方法就可以在Java中被訪問了。