In depth analysis of the address of Java objects

In traditional Java programming, you will no longer need to process Java objects or locations from memory. When you discuss this in the forum, the first question is why do you need to know the address of Java objects? It is an effective problem. But in the past, we reserved the right to conduct experiments. There is nothing wrong with exploring the unknown. I came up with an experiment using sun's package. Unsafe belongs to sun Misc package. This package may be a little strange to you. Look at the source code and methods, and you can know what I mean.

Java's security management provides enough hiding to ensure that you can't manipulate memory so easily. As a first step, I thought of getting the memory location of a Java object. Until exploration, I used to be 100% confident that it was impossible to find the address of the object in Java.

Sun's unsafe The Java API documentation shows that we have the opportunity to get the address using the objectfieldoffset method. This method seems to say, "the class storage in the report allocates its location in a specific field." it also says, "this is just one of the accessor's cookies passed to the unsafe heap memory "Anyway, I can allocate the memory location of an object from its class storage. You can argue that what we get is not the absolute physical memory address of an object. However, we get the logical memory address. The following program will be interesting to you!

As a first step, I have to get an object of the unsafe class. This is difficult because constructors are private. There is a method named getunsafe that returns unsafe objects. Java security management requires you to give source code privileges. I used a little reflection and got an example. I know there are better ways to get examples, but I chose the following methods to bypass security management.

Using unsafe objects, you only need to call objectfieldoffset and staticfieldoffset. The result is the memory allocation address of the class.

The following example program can run on jdk1 6.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>