This is the second part of the JVM Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 — Getting object address

Last time we saw how to read object address. We can use similar trick to read object contents as integers. Let’s see this:

First, we create new object and set some dummy values. Next, we create helper instances for reflection.

In line 27 we do the same trick as last time. We assign object to a long field which in turn assigns reference. So we have an address.

Now, we would like to create an array of integers which would contain the object. This is a common trick, since array can be used to read the values, we can effectively use array as a pointer. Very similar to base pointer or segment address.

So we could assign the foo object directly to that array but then we wouldn’t be able to read first field. That’s because first field would be internally storing array size. We need to move back by one long value, so in line 28 we calculate address of the fake array.

Next, in line 29 we just assign this fake object to int[] field.

Finally, we can read all values using loop.

Obviously, this is very hacky approach and cannot be considered reliable. It highly depends on the architecture, JVM parameters (whether OOP are compressed or not) and multiple other scenarios.