gpt4 book ai didi

java - Java 一定要编译成字节码吗?

转载 作者:搜寻专家 更新时间:2023-10-31 19:59:48 24 4
gpt4 key购买 nike

Java 语言规范是否强制要求将 Java 编译为 Java 字节码?

据我了解,情况并非如此:

JLS 1

Compile time normally consists of translating programs into a machine-independent byte code [representation.

[...]

The Java programming language is normally compiled to the bytecode instruction set and binary format defined in The Java Virtual Machine Specification, Java SE 9 Edition.

(强调我的)

我在规范中找不到任何其他提及“字节码”或“字节码”的地方。

这是否意味着所有字节码操作在技术上都未包含在 JLS 定义的“Java 语言”中并且在技术上依赖于实现细节?

最佳答案

您没看错,术语“通常”以及 JLS 中没有任何字节代码描述的目的是将 Java 编程语言定义为尽可能独立于执行环境。不过,这并不容易:

Relationship to Predefined Classes and Interfaces

As noted above, this specification often refers to classes of the Java SE platform API. In particular, some classes have a special relationship with the Java programming language. Examples include classes such as Object, Class, ClassLoader, String, Thread, and the classes and interfaces in package java.lang.reflect, among others. This specification constrains the behavior of such classes and interfaces, but does not provide a complete specification for them. The reader is referred to the Java SE platform API documentation.

Consequently, this specification does not describe reflection in any detail. Many linguistic constructs have analogs in the Core Reflection API (java.lang.reflect) and the Language Model API (javax.lang.model), but these are generally not discussed here. For example, when we list the ways in which an object can be created, we generally do not include the ways in which the Core Reflection API can accomplish this. Readers should be aware of these additional mechanisms even though they are not mentioned in the text.

所以 Java 编程语言不仅仅是 JLS,它还是 Java SE 平台 API。在那里,我们有提到的 ClassLoader 类的 defineClass 方法,接受类文件格式的输入。因此,即使我们使用字节码格式的类文件以外的其他部署方式,完全兼容的环境也必须在此处支持该格式。请注意,Java 9 引入了 another method accepting input in the class file format,它甚至不需要反射或实现自定义类加载器。

这排除了 JavaME,它没有 JLS 提到的这些 API 工件,否则,我们已经有一个不支持字节码操作的 Java 环境示例。

但这仍然不能完全回答字节码操作是否属于 JavaSE 或 EE 语言之外的问题。即使标准 API 提供了对字节码格式的支持,字节码操作也取决于实现细节,要么是支持非强制性的 Instrumentation API,要么以部署形式处理已编译的类文件,如文件层次结构、jar 文件或模块文件,既不保证是应用程序的部署形式(如开头所述)。因此,确实不可能实现保证所有可能的 Java 环境一起工作的字节码操作工具,尽管您必须竭尽全力创建一个 fully compliant, but not working with these tools 环境……

关于java - Java 一定要编译成字节码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com