Java-@Native

看Object的源码的时候发现了从未见过的修饰符native,雨伞学习一下。

就是这几个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static native void registerNatives();
public final native Class<?> getClass();
public native int hashCode();
@HotSpotIntrinsicCandidate
public final native void notify();

@HotSpotIntrinsicCandidate
public final native void notifyAll();


public final void wait() throws InterruptedException {
wait(0L);
}


public final native void wait(long timeoutMillis) throws InterruptedException;


public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
...
}

参考博客https://www.cnblogs.com/KingIceMou/p/7239668.html

被native修饰的方法就是不是由java实现的,而是由C或者C++实现,并且编译成了dll,然后由java调用,调用过程如下:

实现步骤

  1、在Java中声明native()方法,然后编译;
  2、用javah产生一个.h文件;
  3、写一个.cpp文件实现native导出方法,其中需要包含第二步产生的.h文件(注意其中又包含了JDK带的jni.h文件);
  4、将第三步的.cpp文件编译成动态链接库文件;
  5、在Java中用System.loadLibrary()方法加载第四步产生的动态链接库文件,这个native()方法就可以在Java中被访问了。