②、程序不再是绝对安全的,本地代码的不当使⽤可能导致整个程序崩溃。⼀个通⽤规则是,你应
该让本地⽅法集中在少数⼏个类当中。这样就降低了JAVA和C之间的耦合性。
⽬前来讲使⽤ JNI 的缺点相对于优点还是可以接受的,可能后⾯随着 Java 的技术发展,我们不在需
要 JNI,但是⽬前 JDK 还是⼀直提供对 JNI 标准的⽀持。
3、⽤C语⾔编写程序本地⽅法
上⾯讲解了什么是 JNI,那么我们接下来就写个例⼦,如何⽤ Java 代码调⽤本地的 C 程序。
官⽅⽂档如下:https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jniTOC.html
步骤如下:
①、编写带有 native 声明的⽅法的java类,⽣成.java⽂件;(注意这⾥出现了 native 声明的⽅法关
键字)
②、使⽤ javac 命令编译所编写的java类,⽣成.class⽂件;
③、使⽤ javah -jni java类名 ⽣成扩展名为 h 的头⽂件,也即⽣成.h⽂件;
④、使⽤C/C++(或者其他编程想语⾔)实现本地⽅法,创建.h⽂件的实现,也就是创建.cpp⽂件实
现.h⽂件中的⽅法;
⑤、将C/C++编写的⽂件⽣成动态连接库,⽣成dll⽂件;
下⾯我们通过⼀个 HelloWorld 程序的调⽤来完成这⼏个步骤。
注意:下⾯所有操作都是在所有操作都是在⽬录:D:\JNI 下进⾏的。
⼀、编写带有 native 声明的⽅法的java类
⽤ native 声明的⽅法表示告知 JVM 调⽤,该⽅法在外部定义,也就是我们会⽤ C 语⾔去实现。
System.loadLibrary("helloJNI");加载动态库,参数 helloJNI 是动态库的名字。我们可以这样理解:
程序中的⽅法 helloJNI() 在程序中没有实现,但是我们下⾯要调⽤这个⽅法,怎么办呢?我们就需要对
这个⽅法进⾏初始化,所以⽤ static 代码块进⾏初始化。
这时候如果我们直接运⾏该程序,会报“A Java Exception has occurred”错误:
public class HelloJNI {
//native 关键字告诉 JVM 调⽤的是该⽅法在外部定义
private native void helloJNI();
static{
System.loadLibrary("helloJNI");//载⼊本地库
}
public static void main(String[] args) {
HelloJNI jni = new HelloJNI();
jni.helloJNI();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13