文末有源码
1 java 文件中定义native方法
```
public class test{
static{
System.load("绝对路径/test.so");
}
public static native String hello();
public static void main(String[] args) {
System.out.println((new test()).hello());
}
}
```
2 javah 生成头文件,注意这里javah命令会自动寻找test的类名,不需要指定文件后缀
```
javah -jni test
```
3 当前目录中贴一份jni.h文件和jni_md.h文件,可以去jdk目录找(如果你的jdk是源码形式才有), 否则去网上下载一个jni.h文件即可
4 创建test.cpp 实现test.h中定义的方法
```
#include "jni.h"
#include "test.h"
JNIEXPORT jstring JNICALL Java_test_hello
(JNIEnv *env, jclass j){
return env->NewStringUTF("aaa");
}
```
5 创建动态链接库
```
g++ -fpic -shared -o test.so test.cpp
```
6 编译运行test.java
```
javac test.java
java test
```