Java的本地方法在哪里定义?

时间:2013-04-18 20:58:32

标签: java linux networking java-native-interface native-code

我在CentOS服务器上安装了安装了JRE(1.6_34)的64位Linux发行版。我下载了源代码并深入到java.net.SocketInputStream类。

该类有一个名为socketRead0的方法:

/** 
 * Reads into an array of bytes at the specified offset using
 * the received socket primitive. 
 * @param fd the FileDescriptor
 * @param b the buffer into which the data is read
 * @param off the start offset of the data
 * @param len the maximum number of bytes read
 * @param timeout the read timeout in ms
 * @return the actual number of bytes read, -1 is
 *          returned when the end of the stream is reached. 
 * @exception IOException If an I/O error has occurred.
*/
private native int socketRead0(FileDescriptor fd, 
        byte b[], int off, int len, int timeout)
        throws IOException;

在执行此SocketInputStream#socketRead0方法时,我在哪里可以找到执行的本机源代码?提前谢谢!

3 个答案:

答案 0 :(得分:2)

正如其他答案中所解释的,native方法实际上是C函数,通过JNI调用。包含C函数的库文件通常加载System.loadLibrary并导出遵循JNI命名方案(前缀为Java_),后跟包,类和方法名称,带下划线而不是点)自动链接到那些native Java方法。

但是,其他答案没有提到将C函数链接到native Java方法的第二种方法:RegisterNatives。此接口可用于提供C实现,而无需使用JNI命名方案调用System.loadLibrary,甚至可以导出这些函数。

答案 1 :(得分:1)

在OpenJDK中它是here由于某种原因,我无法找到Linux实现。通常搜索本机文件夹。你的文件将在其中

答案 2 :(得分:0)

native方法表示此方法不是Java代码,而是 native 代码-a.k.a.机器代码 - 通常用C / C ++编写。通过JNI调用此类函数。

您应该搜索它加载它使用的本机库的位置,如

System.loadLibrary("nameOfLibrary");

此本机库应该导出Java的函数,如

JNIEXPORT returnType JNICALL Java_ClassName_methodName
相关问题