什么是Java中的本机实现? [英] What is a native implementation in Java?

查看:90
本文介绍了什么是Java中的本机实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们查看Java Object类,那么我们可以找到一些方法,如:

If we look at the Java Object class then we can find some of the methods like:

public native int hashCode()
protected native Object clone()

这些原生代码是什么以及这些方法如何工作?

What are these natives and how do these methods work?

推荐答案

这些方法是 Intrinsic 或在本机代码中用Java编写,即,特定于给定的机器。

These methods are either Intrinsic or written outside Java in "native" code, that is, specific to the given machine.

您提到的是 Intrinsic 和JDK的一部分,但您也可以使用 Java Native Interface (JNI)。这通常使用C来编写方法,但是许多其他语言(例如python)允许您以相当容易的方式编写方法。代码是以这种方式编写的,无论是为了提高性能,还是因为它需要访问平台特定的基础结构而无法在普通的java中完成。

The ones you mention are Intrinsic and part of the JDK but you can also write native methods yourself using the Java Native Interface (JNI). This would normally use C to write the methods, but a lot of other languages, such as python allow you to write methods this way fairly easily. Code is written this way either for performance, or because it needs to access platform specific infrastructure which cannot be done in plain java.

hashcode(),这是由JVM实现的。这是因为哈希码通常只与JVM知道的东西有关。在早期的JVM中,这与对象在内存中的位置有关 - 在其他JVM上,Object可能在内存中移动,因此可能会使用更复杂(但仍然非常快)的方案。

In the case of hashcode(), this is implemented by the JVM. This is because often the hashcode will be related to something only the JVM knows. On early JVMs this was related to the object's location in memory - on other JVMs the Object may move in memory, and so a more complicated (but still very fast) scheme may be used.

这篇关于什么是Java中的本机实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆