在非常多情況下,java須要調用其它語言的代碼,比方c的代碼。那么這個時候java中native方法就發揮作用了。以下就介紹native方法的使用。
一、JNI使用流程
a.編寫帶有native聲明的方法的Java類
b.使用javac命令編譯編寫的Java類
c.使用java -jni ****來生成后綴名為.h的頭文件
d.使用其它語言(C、C++)實現本地方法
e.將本地方法編寫的文件生成動態鏈接庫
二、實踐
1、編寫類代碼
package com.sunny.demo; public class Demo01 { public native void hello();//沒有實現 static{ System.loadLibrary("hello");//在類載入的 時候載入dll } public static void main(String[] args){ new Demo01().hello(); } }
2、編譯
javac com/sunny/demo/Demo01.java(注意,我這里是帶包編譯)
3、生成.h文件
javah -jni com.sunny.demo.Demo01(注意。頭文件生成文件夾的位置。不知.java文件的位置,而在和包同級文件夾中,這里生成的文件名稱為com_sunny_demo_Demo01.h)
4、用c實現hello方法(vc++6.0新建dllproject)
(1)當中com_sunny_demo_Demo01.h中代碼例如以下(javah自己主動生成的)
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_sunny_demo_Demo01 */ #ifndef _Included_com_sunny_demo_Demo01 #define _Included_com_sunny_demo_Demo01 #ifdef __cplusplus extern "C" { #endif /* * Class: com_sunny_demo_Demo01 * Method: hello * Signature: ()V */ JNIEXPORT void JNICALL Java_com_sunny_demo_Demo01_hello (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
(2).c文件,實現hello方法
#include<stdio.h> #include"hello.h" JNIEXPORT void JNICALL Java_com_sunny_demo_Demo01_hello(JNIEnv * a, jobject b){ printf("hello world"); }
(3)用VC++6.0編譯一下在debug文件夾中就生成好了dll文件。
說明:編譯時假設產生例如以下錯誤:fatal error C1083: Cannot open include file: 'jni.h': No such file or directory。說明沒有找到jni.h。到jdk的安裝文件夾 include/jni.h;win32/jni_md.h;win32/jawt_md.h這3個文件復制到vc的安裝文件夾include中
5.將dll放到生成.h的那一集文件夾中。執行java com.sunny.demo.Demo01就會出現例如以下結果
三、總結:
上面的樣例中,我是帶包編譯的,所以文件存放和生成的位置一定要注意,在java層面我們僅僅須要dll文件,.h和.cd 文件的目的僅僅是為了生成dll文件.最后給出我代碼的文件夾結果
.h文件是javah生成的,dll文件是應該放的位置(假設不放在這個位置。執行報錯,找不到hello這個庫)
dll參考文章:http://www.cnblogs.com/chio/archive/2007/11/03/948480.html
external c :http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html
java native文章: http://blog.163.com/yueyemaitian@126/blog/static/21475796200701491621267