本机方法和平台独立性
Native methods and platform independency
这是从 Java 的 public static native long currentTimeMillis()
方法 java.lang.System
class 的源代码中提取的注释。
* 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.
从这条评论中可以明显看出,此本机方法的行为取决于平台。如果是这种情况,我们是否应该避免在 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?
没有。这不是从中吸取的正确教训。
Javaclass库的很多功能最终都依赖于本地调用。如果您决定避免调用本机方法,那么(首先)您的程序将无法执行任何操作 I/O。这会使 Java 不切实际。而在时间的情况下,如果你避免了所有的原生方法,那么你将根本无法获得时间。
一些标准 Java API 具有平台特定行为的真正原因是平台本身存在差异。如果不过度限制应用程序的功能,就无法 隐藏差异。
在您的示例中,评论解释了不同操作系统提供的系统时钟具有不同的粒度时间度量。这是无法回避的事实。隐藏它(以 "portability" 的名义)的唯一方法是人为地 减少 提供毫秒或更好分辨率的系统的粒度。这对于需要最大可用分辨率的人来说是不可接受的。
正确的教训 (IMO) 如下:
您需要阅读并理解 javadocs 关于平台特定行为的实际说法。
然后您需要设计您的应用程序,使其不依赖于特定于平台的行为。例如,如果您需要最大的可移植性,请不要将您的应用程序设计为依赖毫秒粒度时钟。
尽可能使用处理平台细节的 API。例如,在操作文件系统路径名时使用 File
或 Path
而不是字符串攻击。
这是从 Java 的 public static native long currentTimeMillis()
方法 java.lang.System
class 的源代码中提取的注释。
* 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.
从这条评论中可以明显看出,此本机方法的行为取决于平台。如果是这种情况,我们是否应该避免在 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?
没有。这不是从中吸取的正确教训。
Javaclass库的很多功能最终都依赖于本地调用。如果您决定避免调用本机方法,那么(首先)您的程序将无法执行任何操作 I/O。这会使 Java 不切实际。而在时间的情况下,如果你避免了所有的原生方法,那么你将根本无法获得时间。
一些标准 Java API 具有平台特定行为的真正原因是平台本身存在差异。如果不过度限制应用程序的功能,就无法 隐藏差异。
在您的示例中,评论解释了不同操作系统提供的系统时钟具有不同的粒度时间度量。这是无法回避的事实。隐藏它(以 "portability" 的名义)的唯一方法是人为地 减少 提供毫秒或更好分辨率的系统的粒度。这对于需要最大可用分辨率的人来说是不可接受的。
正确的教训 (IMO) 如下:
您需要阅读并理解 javadocs 关于平台特定行为的实际说法。
然后您需要设计您的应用程序,使其不依赖于特定于平台的行为。例如,如果您需要最大的可移植性,请不要将您的应用程序设计为依赖毫秒粒度时钟。
尽可能使用处理平台细节的 API。例如,在操作文件系统路径名时使用
File
或Path
而不是字符串攻击。