Java 中的本机方法是什么以及它们应该在哪里使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18900736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:09:30  来源:igfitidea点击:

What are native methods in Java and where should they be used?

javanative

提问by niks

A native method has the same syntax as an abstract method, but where is it implemented?

本机方法与抽象方法具有相同的语法,但它在哪里实现?

回答by Peter Lawrey

I like to know where does we use Native Methods

我想知道我们在哪里使用本地方法

Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.

理想情况下,根本没有。实际上,某些功能在 Java 中不可用,您必须调用一些 C 代码。

The methods are implemented in C code.

这些方法是用 C 代码实现的。

回答by Laurence Gonsalves

The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

该方法是在“本机”代码中实现的。也就是说,不在 JVM 中运行的代码。它通常用 C 或 C++ 编写。

Native methods are usually used to interface with system calls or libraries written in other programming languages.

本机方法通常用于与系统调用或用其他编程语言编写的库进行交互。

回答by Zac

Native methods allow you to use code from other languages such as C or C++ in your java code. You use them when java doesn't provide the functionality that you need. For example, if I were writing a program to calculate some equation and create a line graph of it, I would use java, because it is the language I am best in. However, I am also proficient in C. Say in part of my program I need to calculate a really complex equation. I would use a native method for this, because I know some C++ and I know that C++ is much faster than java, so if I wrote my method in C++ it would be quicker. Also, say I want to interact with another program or device. This would also use a native method, because C++ has something called pointers, which would let me do that.

本机方法允许您在 Java 代码中使用来自其他语言(例如 C 或 C++)的代码。当 java 不提供您需要的功能时,您可以使用它们。例如,如果我正在编写一个程序来计算一些方程并创建它的折线图,我会使用 java,因为它是我最擅长的语言。但是,我也精通 C。说我的一部分程序我需要计算一个非常复杂的方程。我会为此使用本机方法,因为我知道一些 C++ 并且我知道 C++ 比 java 快得多,所以如果我用 C++ 编写我的方法,它会更快。另外,假设我想与另一个程序或设备进行交互。这也将使用本机方法,因为 C++ 有一种叫做指针的东西,它可以让我这样做。

回答by Cjo

Java native code necessities:

Java本机代码的必要性:

  • h/w access and control.
  • use of commercial s/w and system services[h/w related].
  • use of legacy s/w that hasn't or cannot be ported to Java.
  • Using native code to perform time-critical tasks.
  • 硬件访问和控制。
  • 使用商业软件和系统服务[硬件相关]。
  • 使用尚未或无法移植到 Java 的遗留软件。
  • 使用本机代码执行时间紧迫的任务。

hope these points answers your question :)

希望这些要点能回答你的问题:)