java - native 方法和平台独立性

标签 java native-methods platform-independence

这是从 java.lang.System 类的 Java public static native long currentTimeMillis() 方法的源代码中提取的注释。

 * Returns the current time in milliseconds.  Note that
 * while the unit of time of the return value is a millisecond,
 * the granularity of the value depends on the underlying
 * operating system and may be larger.  For example, many
 * operating systems measure time in units of tens of
 * milliseconds.

从这个评论中可以明显看出,这个 native 方法的行为是依赖于平台的。如果是这种情况,我们是否应该避免调用 native 方法来用 Java 编写真正与平台无关的代码?

最佳答案

It is obvious from this comment that behavior of this native method is platform dependent.

这是正确的。

If this is the case, should we avoid native method calls for writing truly platform independent code in Java?

没有。这不是从中吸取的正确教训。

Java 类库的许多功能最终都依赖于 native 调用。如果您决定避免调用 native 方法,那么(首先)您的程序将无法执行任何 I/O。这将使 Java 变得不切实际。而就时间而言,如果你避免使用所有原生方法,那么你根本无法获取时间。

某些标准 Java API 具有平台特定行为的真正原因是平台本身存在差异。如果不过度限制应用程序的功能,就无法隐藏这些差异。

在您的示例中,注释解释了不同操作系统提供的系统时钟具有不同的粒度时间度量。这是一个无法回避的事实。隐藏这一点的唯一方法(以“可移植性”的名义)是人为地降低提供毫秒或更好分辨率的系统的粒度。这对于需要最大分辨率的人来说是无法接受的。

正确的学习教训(IMO)如下:

  • 您需要阅读并理解 javadoc 中有关平台特定行为的实际内容。

  • 然后您需要设计您的应用程序,使其不依赖于平台特定的行为。例如,如果您需要最大的可移植性,请勿将应用程序设计为依赖于毫秒粒度时钟。

  • 如果可能,请使用处理平台特定信息的 API。例如,在操作文件系统路径名时,使用 FilePath 而不是 string bashing。

关于java - native 方法和平台独立性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949154/

相关文章:

java - 奇怪的java jvm内存不足

java - 使用颜色代码设置 swing 组件的前景

java - ACTION_MEDIA_BUTTON 的广播接收器不起作用

java - Spring Cloud Contract 和两个既是生产者又是消费者的服务

c# - TestDriven.NET 和 native C 库

c# - C# 中的 NativeMethods 类有什么作用?

screen-orientation - 使用 powershell 更改屏幕方向 - 注册表值存储在哪里?

operating-system - 程序如何执行?操作系统在哪里发挥作用?

c++ - 不改变框架的平台独立并行化?