lets say i have this variable :
...
Somekindofobject var = new Somekindofobject();
...
and i want to know where var is located on the heap ( by address , like 0x08 and so on),and to print the address out .
is it possible?
It is impossible to get an address of any primitive variable or object in Java. All that you can do is get default object hash code (which usually related to its address, but it is not guaranteed) with System. identityHashCode(a) .
@Peter Lawrey: Yes, you can access memory relative to an object (to read instance fields) or access memory at an absolute location. Objects get moved around in memory, so the address of an object has limited meaning.
Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory. These objects have global access and we can access them from anywhere in the application.
Stack is stores only primitive data types and addresses pointing to objects stored on Heap(object references). And all variables created on Stack are local and exists only while function executes, this concepts is called "variable scope"(local and global variables).
i am working on a program that gets as input java program , and instruments code that prints out to file information about variable access. The only way that i can determine between two fields of objects of the same class is by thier address on heap. Therefore, i need the address on heap
You can use System.identityHashCode
to get a notion of sameness.
It's not perfect, but it's pretty good.
If you do get the heap address of an object, remember that the JVM is allowed to move objects around (and frequently does when a generational garbage collector promotes a long lived object to an older generation) so the heap location of an object is not a good proxy for identity in all circumstances.
You might give a try on this article of javaPaper: Address of a Java object
It's about using the Unsafe
class in the sun.misc
package to get the address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With