Address of a Java Object

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.

Ads by Google

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

This Core Java tutorial was added on 05/07/2010.

«

»

Comments on "Address of a Java Object"

  1. Anu says:

    So surprised…Nice article Joe

    Thanks,
    Anu

  2. zero_cool says:

    Amazing!
    It workss!! Thanks!

  3. prateek kanujiya says:

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

  4. Srinivas says:

    Interesting article

  5. 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 ??

    • 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)

  6. Anonymous says:

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

  7. Anonymous says:

    Informative and good one!

  8. 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

  9. 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 ……..

  10. dhaval says:

    Great ….tutorial..!!

  11. Swapnil says:

    Brilliant.. :)

  12. Sathyaraj says:

    Nice Tutorial:)

  13. Praveen says:

    Intresting Tutorial !!

  14. O. L. says:

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

  15. 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!

  16. praveen rohal says:

    good job

  17. 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.

  18. chandra says:

    very simple and good

  19. anil says:

    Nice Explanation…

  20. padmaraju says:

    hey its GOOD. keep it up.

  21. Thangavel L Nathan says:

    Hi !!

    Its good article.. Keep on growing…

    Best of luck !!!

  22. PANKAJ SINHA says:

    awesome work….thnxx for such kind of post

  23. Alpna says:

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

  24. shampa says:

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

  25. Robin says:

    Great information…Please keep sharing more stuffs

  26. gr8 says:

    Good Info. Thx..

  27. Mani says:

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

  28. 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

  29. Sana says:

    Nice article.
    Keep it up… :)

  30. Swati says:

    Hey thanks for posting this valuable info.

  31. Vinod Gulia says:

    great info..thanks keep on sharing…

  32. Mahender says:

    interesting tutorial

  33. Ajai says:

    Nice article.
    Expecting a lot more :)

  34. Anuradha says:

    nice expermentation, keep going

  35. Saravanan says:

    Thanks for sharing….

  36. Chankey Pathak says:

    Keep experimenting and posting :-)

  37. shaik muhammad says:

    nice exploration

  38. ajay malhotra says:

    nice info….

  39. Jagdish says:

    Thanks for sharing, keep going………

  40. Anubha says:

    Great info!

  41. Geetha says:

    Nice try. Keep it going.

  42. Imdad says:

    Good tutorial

Your Comment