class - JVM 如何决定一个类 “belongs”(例如内部类或嵌套类)是否属于另一个类?

标签 class language-agnostic jvm bytecode vm-implementation

我想更好地理解类文件和内部/嵌套类,我想知道以下几点:

  • InnerClasses属性用于引用“包含”类中的内部/嵌套类,还是在内部/嵌套类中用于引用“容器”类?
  • InnerClasses类文件中的属性是否足够?例如。内部/嵌套类是否必须遵循 $ 的名称修饰?或者这只是一个约定?
  • 有没有办法在不设置 InnerClasses 的情况下使类看起来像 JVM 的内部/嵌套类?属性,这是否取决于 JLM 供应商? (我记得听说 IBM 的实现在某些方面要求不那么严格。)
  • JVM 的类加载机制与 Java 反射有多大的交互作用?是否有可能使 JVM 不同意 Java 反射的结果?

  • 我尝试在 JVM 规范中查找它,但没有找到实际机制的描述。

    我只在“The InnerClasses Attribute”中找到这句话远程连接到我的问题:

    The Java virtual machine does not currently check the consistency of the InnerClasses attribute with any class file actually representing a class or interface referenced by the attribute.

    最佳答案

    对上一个答案的一些补充:

    Is the InnerClasses attribute used to store the contained inner/nested classes in the containing class or is it used in the inner/nested classes to refer to the ‘container’ class?


    每个已编译类的字节码都存储在一个单独的 .class 文件中。实际的“内部类”不存储在该属性中。正如上一篇文章所指出的,该属性仅指向编译器在创建字节码时知道的类。

    Is the InnerClasses attribute in class files sufficient? E.g. Do inner/nested classes have to follow the name mangling with $ or is this just a convention?

    Is there a way to make a class look like an inner/nested class to the JVM without setting the InnerClasses attribute and does this depend on the JLM vendor? (I remember hearing that IBM's implementation had less strict requirements in some parts.)


    对于这两个问题,我都不确定。但我认为内部/嵌套类的概念是 Java 语言(因此 Java 编译器提供)的东西。在字节码中,声明为普通公共(public)类的类与某些嵌套类或内部类之间不应有任何区别。
    您可以轻松地尝试给定的虚拟机如何处理这个问题,如下所示:
  • 创建一个包含一些嵌套类和内部类的类
  • 编写一个小程序,尝试通过定义类范围之外的反射来加载和实例化其中一个内部类。您必须在此处使用反射,因为 Java 编译器不允许您实例化不在范围内的嵌套类!如果您可以成功实例化该类,则证明 VM 在内部不会以不同方式处理嵌套类和普通类。

  • How much does the class loading mechanism of the JVM interact with Java reflection? Would it be possible to make the JVM disagree with the results from Java reflection?


    我不明白最后这个问题。当您说虚拟机和反射应该不同意时,您能否解释一下您的意思?

    关于class - JVM 如何决定一个类 “belongs”(例如内部类或嵌套类)是否属于另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082142/

    相关文章:

    css - 类名的 JavaFX 样式

    algorithm - "classical algorithms"的真实世界实现

    language-agnostic - 当我定义函数时,我应该以什么顺序放置参数?

    java.lang.VerifyError - 当类的静态变量包含对类实例的引用时

    java - 写Java代码让java虚拟机崩溃

    java - Java:数组操作函数中的错误

    java - 我在用 Java 创建交互式菜单时遇到问题

    java - 为什么java找不到我的方法?

    database-design - IETF 语言代码应该使用什么数据类型?

    gradle - gradle如何获取第三方库的所有依赖关系?