Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to print the reference of an Integer Object?

Suppose

Integer integerA = 500;

I would like to print the reference returned.

like image 870
Code Enthusiastic Avatar asked Dec 25 '22 23:12

Code Enthusiastic


1 Answers

To get the reference to the object as a number you can use Unsafe on JVMs which support it. You can place the reference in an array and access it with Unsafe.getInt() for 32-bit references (Note: most 64-bit JVMs will be using 32-bit references) or Unsafe.getLong() This will access the reference as a number, but it could change as soon as you get it if a GC occures and the object is moved.

Another complication is that CompressedOops means the index to the object can be translated a number of different ways. To keep things simple, I suggest using a heap of 4 GB to 26GB. For these sizes, you shift the address by << 3 to get the address.

BTW You can use Unsafe.putInt(x, 1, hashCode) to overwrite the system hashCode. ;)

like image 127
Peter Lawrey Avatar answered Jan 16 '23 00:01

Peter Lawrey