Address of a Java Object

Last modified on July 1st, 2019 by Joe.

In conventional java programming, you will never need address or location of a java object from memory. When you discuss about this in forums, the first question raised is why do you need to know the address of a java object? Its a valid question. But always, we reserve the right to experiment. Nothing is wrong in exploring uncharted areas.

I thought of experimenting using a little known class from sun package. Unsafe is a class that belongs to sun.misc package. For some of you the package might be new. You need not worry about it. If you have sun’s JDK then you have this class already.

When a class name is “Unsafe” in java, it calls for your attention immediately. Then I decided to dig deep into it and find what is unsafe about that class. Voila, it really opens up the pandora’s box. Its difficult to find the source of Unsafe. Get the source and look at the methods you will know what I am referring to.

Java’s security manager provides sufficient cover and ensures you don’t fiddle with memory that easily. As a first step, I thought of getting the memory location of a java object. Until the exploration, I too was 100% confident that it was not possible to find the location / address of an object in java.

Sun’s Unsafe.java api documentation shows us an opportunity to get the address using the method objectFieldOffset. That method says, “Report the location of a given field in the storage allocation of its class“. It also says, “it is just a cookie which is passed to the unsafe heap memory accessors“. Whatsoever, I am able to get the storage memory location of an object from the storage allocation of its class.

You can argue that, what we have got is not the absolute physical memory address of an object. But we have got the logical memory address. The following program will be quite interesting for you!

As a first step, I have to get an object of Unsafe class. It is quite difficult as the constructor is private. There is a method named getUnsafe which returns the unsafe object. Java’s security manager asks you to make your java source code privileged. I used little bit of reflection and got an instance out. I know there are better ways to get the instance. But to bypass the security easily I chose the following.

Using Unsafe’s object just invoke objectFieldOffset and staticFieldOffset. The result is address / location of object in the storage allocation of its class.

Following example program runs well on JDK 1.6

import sun.misc.Unsafe;
import java.lang.reflect.Field;

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);
 }
}

Comments on "Address of a Java Object"

  1. Imdad says:

    Good tutorial

  2. Geetha says:

    Nice try. Keep it going.

  3. Anubha says:

    Great info!

  4. Jagdish says:

    Thanks for sharing, keep going………

  5. ajay malhotra says:

    nice info….

  6. shaik muhammad says:

    nice exploration

  7. Chankey Pathak says:

    Keep experimenting and posting :-)

  8. Saravanan says:

    Thanks for sharing….

  9. Anuradha says:

    nice expermentation, keep going

  10. Ajai says:

    Nice article.
    Expecting a lot more :)

  11. Mahender says:

    interesting tutorial

  12. Vinod Gulia says:

    great info..thanks keep on sharing…

  13. Swati says:

    Hey thanks for posting this valuable info.

  14. Sana says:

    Nice article.
    Keep it up… :)

  15. Sneha says:

    Hi Nice Try..

    When try executing the given program getting the below error..

    Access restriction: The type Unsafe is not accessible due to restriction on required library C:\Program Files
    \Java\jre6\lib\rt.jar

  16. Mani says:

    Superb try! very nice! Keep it up!!!!!

  17. gr8 says:

    Good Info. Thx..

  18. Robin says:

    Great information…Please keep sharing more stuffs

  19. shampa says:

    Your concets are really great.I became a fan of ur tutorial. Keep it up

  20. Alpna says:

    Really gud article.. its nice 2 read ur all articles.Keep it up !!!

  21. PANKAJ SINHA says:

    awesome work….thnxx for such kind of post

  22. Thangavel L Nathan says:

    Hi !!

    Its good article.. Keep on growing…

    Best of luck !!!

  23. padmaraju says:

    hey its GOOD. keep it up.

  24. anil says:

    Nice Explanation…

  25. chandra says:

    very simple and good

  26. Ramesh says:

    The output of the java program is not the address of the field(s) but the offset of the field in the object.

  27. praveen rohal says:

    good job

  28. N.ZAZA says:

    Well you CAN get an object’s address in physical memory using JNI. I realize this is a relatively old post, but if you are still interested let me know!

  29. O. L. says:

    N. ZAZA I am interested in getting the physical address in JNI any tips?

  30. Praveen says:

    Intresting Tutorial !!

  31. Sathyaraj says:

    Nice Tutorial:)

  32. Swapnil says:

    Brilliant.. :)

  33. dhaval says:

    Great ….tutorial..!!

  34. Muhammad says:

    Hello Everybody,
    this is a great tutorial for me and i learn a lot from this .Today
    this question is asked to me in interview ……..

  35. Arvind says:

    Hi Nice Try..

    When try executing the given program getting the below error..

    Access restriction: The type Unsafe is not accessible due to restriction on required library C:\Program Files
    \Java\jre6\lib\rt.jar

    plz tell me what this mean basically

  36. Anonymous says:

    Informative and good one!

  37. Anonymous says:

    Misleading. This only finds an offset within the class/object, not an actual location of anything in memory.

  38. Mukul Kumar says:

    Suppose we make a class in a java prog and when we initialize an object of that class in other class in same package and when i write code as
    Box b1=new box();
    System.out.println(b1);
    it gives us an o/p which seems as the address of that object.
    is it correct and if correct why ??

  39. Prabhdeep says:

    No, its not the address of the object. Its just a string representation of the object. Which consists of class name and the hash code in hexadecimal format.

    getClass().getName() + ‘@’ + Integer.toHexString(hashCode())

    (Source: JavaDocs)

  40. Srinivas says:

    Interesting article

  41. prateek kanujiya says:

    It’s good one but it is only offset of object address……..can you please provide the physical address…

  42. zero_cool says:

    Amazing!
    It workss!! Thanks!

  43. Anu says:

    So surprised…Nice article Joe

    Thanks,
    Anu

Comments are closed for "Address of a Java Object".