一个对象可以包含对其他对象的引用。如果将这些引用声明为类/字段变量,那么当对象本身在堆上创建时,字段引用表示的值将存储在堆上。
如果我有
public class A {
int size;
}
- 我知道如果 size 得到
2
的 int 值,那么它将作为对象的一部分存储在堆上,但是引用在哪里,即名称 size 存储在哪里? - 名称“size”是否也存储在堆上的对象内部。
- JVM 如何在堆上交叉引用
size == 2
? - 当您加载它在主线程中运行的类时,每个线程都有自己的堆栈。那么这些字段引用不是在主堆栈上创建的吗?
最佳答案
Where is the name "size" stored?
字段的名称存储在类对象 A.class
中。您可以使用 java.lang.reflect
检查类字段名称图书馆。
例如,要检查一个类的所有字段,请执行以下操作:
for (Field field : A.class.getFields()) {
String fieldName = field.getName();
Class<?> fieldClass = field.getType();
// etc
}
Is the name "size" also stored inside of the object on the heap?
没有。它存储在permgen
内存中
How does JVM cross-reference size == 2 on the heap?
它在编译时查找字段,其余的发生在字节码中
Field references are not created on the main stack?
没有。除了heap和stack之外还有更多的内存区域,还有permgen,里面存放类定义和类字段。还有更多内存区域,例如用于垃圾收集器。
关于java - 本地引用和字段引用内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11680067/