浅谈Object类中的registerNatives方法

前言——本地方法

一直以来,都没有搞懂registerNatives()的作用,直到现在也没有全面理解。心细的道友应该能发现不仅仅是Object类,还有System类,Class类,ClassLoader类,UnSafe类等等,都能在类源码中找到如下代码:

private static native void registerNatives();
    static {
        registerNatives();
    }

在《深入Java虚拟机》这本书的1.3.1节对Java方法有以下描述:

Java有两种方法:Java方法和本地方法。Java方法是由Java语言编写,编译成字节码,存储在class文件中。本地方法是由其他语言(比如C,C++,或者汇编)编写的,编译成和处理器相关的机器代码。本地方法保存在动态连接库中,格式是各个平台专有的。Java方法是平台无关的,但本地方法不是。运行中的Java程序调用本地方法时,虚拟机装载包含这个本地方法的动态库,并调用这个方法。本地方法是联系Java程序和底层主机操作系统的连接方法。

如何调用本地方法

在《The Java Native Interface Programmer’s Guide and Specification》这本书,书中8.3 Registering Native Methods节有如下几段描述:

Before an application executes a native method it goes through a two-step process to load the native library containing the native method implementation and then link to the native method implementation:

1.System.loadLibrary locates and loads the named native library. For example, System.loadLibrary(“foo”) may cause foo.dll to be loaded on Win32.

2.The virtual machine locates the native method implementation in one of the loaded native libraries. For example, a Foo.g native method call requires locating and linking the native function Java_Foo_g, which may reside in foo.dll.

This section will introduce another way to accomplish the second step.

Instead of relying on the virtual machine to search for the native method in the already loaded native libraries, the JNI programmer can manually link native methods by registering a function pointer with a class reference, method name, and method descriptor:

通过以上内容我们知道一个Java程序要想调用一个本地方法,需要执行两个步骤:

第一,通过System.loadLibrary()将包含本地方法实现的动态文件加载进内存;
第二,当Java程序需要调用本地方法时,虚拟机在加载的动态文件中定位并链接该本地方法,从而得以执行本地方法。
registerNatives()方法的作用就是取代第二步,让程序主动将本地方法链接到调用方,当Java程序需要调用本地方法时就可以直接调用,而不需要虚拟机再去定位并链接。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值