In traditional Java programming, you will no longer need to deal with Java objects or locations from memory. When you discuss this on forums, the first question that comes up is why do you need to know the address of a Java object? It is a valid question. But in the past, we reserved the right to conduct trials. There is nothing wrong with exploring questions in uncharted territory. I came up with an experiment using sun company packages. Unsafe is a package belonging to sun.misc. Maybe this package is a bit unfamiliar to you, take a look at the source code and methods, and you will know what I am referring to.
Java's security management provides enough hiding to ensure that you can't mess with memory so easily. As a first step, I thought of getting the memory location of a Java object. Until exploring, I used to be 100% confident that it was impossible to find the location of the address of an object in Java.
Sun's Unsafe.java API documentation shows that we have access to the address using the method objectFieldOffset. This method seems to be saying, "The class in the report allocates its location in a specific area of storage." It also says, "This is just an accessor where the cookie is passed to unsafe heap memory." Anyway, I am able to allocate the memory location where an object is stored from its class's storage. You could argue that what we get is not the absolute physical memory address of an object. However, we got the logical memory address. The following program will be of great interest 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 called getUnsafe which returns an unsafe object. Java security management requires that you give source code privileges. I used a little bit of reflection and got an instance. I know there are better ways to get an instance, but I chose the following method to bypass security management.
To use Unsafe objects, just call objectFieldOffset and staticFieldOffset. The result is the memory allocation address of the class.
The following example program can run on JDK1.6.
public class ObjectLocation {
private static int apple = 10;
private int orange = 10;
public static void main(String[] args) throws Exception {
Unsafe unsafe = getUnsafeInstance();
Field appleField = ObjectLocation.class.getDeclaredField("apple");
System.out.println("Location of Apple: "
+ unsafe.staticFieldOffset(appleField));
Field orangeField = ObjectLocation.class.getDeclaredField("orange");
System.out.println("Location of Orange: "
+ unsafe.objectFieldOffset(orangeField));
}
private static Unsafe getUnsafeInstance() throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeInstance.setAccessible(true);
return (Unsafe) theUnsafeInstance.get(Unsafe.class);
}
}