简体   繁体   English

Java解释对象如何存储在内存中

[英]Java explain how objects are stored in memory

int x = 5                               Cat luna = new Cat()
Address           Value                 address       reference
669cf9            5                     723ecf        683ec5

If Cat:如果猫:

public class Cat{
  private String name;

  public void talk(){
      System.out.println("meow");
  }
}

How can I show what's at memory address 683ec5?如何显示内存地址 683ec5 处的内容?

Objects are stored in memory as a block of fields with Object headers.对象作为带有对象头的字段块存储在内存中。 You can take a look at jol to see how Objects are actually laid out in memory.您可以查看jol以了解对象在内存中的实际布局。 Each object has header, fields might have padding, fields might take more space than you think ( boolean ), etc.每个对象都有标题,字段可能有填充,字段可能占用比您想象的更多的空间( boolean )等。

You can take a look at this example where I tried to explain things a little more, but the github page about jol is extensive in its examples.你可以看一下这个例子,我试图在其中进一步解释一些事情,但是关于 jol 的 github 页面在它的例子中非常广泛。

At the bytecode level accessing an Object field is boring, to be honest, but you can take a look for sure at what javac produces (with javap ).老实说,在bytecode级别访问 Object 字段很无聊,但是您可以确定javac产生什么(使用javap )。 When code is executed on the CPU, you will see different offsets when trying to get a certain field, like:当代码在 CPU 上执行时,您会在尝试获取某个字段时看到不同的偏移量,例如:

mov    0x10(%rsi),%r10

this is accessing "something" at a certain 16 offset ( 0x10 is an offset here).这是在某个16偏移处访问“某物”(这里的0x10是一个偏移)。 Think about an Object like a stack, accessing fields - you need to know how big each one is (VM tracks that) and the beginning address of the stack, the rest is easy.把一个对象想象成一个堆栈,访问字段 - 你需要知道每个对象有多大(VM 跟踪)和堆栈的起始地址,其余的很容易。

The MUST read here if you really want to know things starts from this page .如果你真的想知道事情从这个页面开始,必须阅读这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM