gpt4 book ai didi

java - Java 字节码中的字段引用

转载 作者:行者123 更新时间:2023-11-30 09:16:53 25 4
gpt4 key购买 nike

我在 Java 字节码规范中发现了一些我不理解的内容。

考虑以下类层次结构:

class FilterOutputStream {
protected OutputStream out;
}

class PrintStream extends FilterOutputStream {
public void write(...) {
out.write(...);
}
}

使用 javap 查看 PrintStream 的字节码,我看到读取 out 字段是这样完成的:

getfield #21

正如预期的那样,引用 #21 是一个字段引用,包含字段的类、名称和描述符。然而,它看起来像这样:

const #21 = Field #30.#204; //  java/io/PrintStream.out:Ljava/io/OutputStream;

这真是令人费解,因为上面说 out 字段是 PrintStream 的成员。这不是真的;它是 FilterOutputStream 的成员,这是我希望在上面的字段引用中看到的类。 JVM 规范非常模糊,但似乎支持我:

The value of the class_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Class_info (§4.4.1) structure representing a class or interface type that has the field or method as a member.

(来自 http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4.2 .)

这对我来说是个问题,因为我查看字段引用,加载类,然后找不到字段。另一方面,Java 编译器确实可以工作,所以显然我的理解是错误的...

有人可以为我澄清一下吗?我是否应该加载该类,查找字段引用,如果没有找到它,则开始处理类层次结构直到找到它?

非常感谢指向规范中描述正确行为的地方...

最佳答案

您错过了 JVM 规范中有关字段查找的部分。如果该字段在当前类中不存在,它将开始搜索父类(super class)和接口(interface)。

5.4.3.2 Field Resolution
To resolve an unresolved symbolic reference from D to a field in a class or interface
C, the symbolic reference to C given by the field reference must first be resolved
(§5.4.3.1). Therefore, any exception that can be thrown as a result of failure of
resolution of a class or interface reference can be thrown as a result of field
resolution. If the reference to C can be successfully resolved, an exception relating
to the failure of resolution of the field reference itself can be thrown.
When resolving a field reference, field resolution first attempts to look up the
referenced field in C and its superclasses:
1. If C declares a field with the name and descriptor specified by the field
reference, field lookup succeeds. The declared field is the result of the field
lookup.
2. Otherwise, field lookup is applied recursively to the direct superinterfaces of
the specified class or interface C.
3. Otherwise, if C has a superclass S, field lookup is applied recursively to S.
4. Otherwise, field lookup fails.

关于java - Java 字节码中的字段引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19237146/

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