This question already has an answer here:
In Java, is there a way to get reference address, say
String s = "hello"
can I get the address of s itself , also, can I get the address of the object which reference refers to?
This question already has an answer here:
In Java, is there a way to get reference address, say
String s = "hello"
can I get the address of s itself , also, can I get the address of the object which reference refers to?
Yes, You can do it with Unsafe, Althrough it's not so directly. Put the object or instance reference into a int[], that's ok. long[] should be fine as well.
You can get the object index with Unsafe. Depending on how the JVM is using the memory (32-bit addresses, 32-bit index, 32-bit index with offset, 64-bit address) can affect how useful the object index is.
Here is a program which assumes you have 32-bit index in a 64-bit JVM.
Running on Java 6 update 26 (64-bit with compressed oops) and Java 7. Note: addresses and relative addresses are in hex.
OR sometimes
It's not possible in Java to get a reference address of an object, like your String. The reference address of an object is hidden to the user, in Java.
In C, you can do this, through the concept of pointers. Java has a similar concept, at low-level,and this is the reference address. The reference is like a C pointer, but it's not explicit. In C, you can do the operation of referencing of pointers, through the
*
, but in Java, it's not possible.I don't like very much the C language, also because the pointers, according to me, are not an easy concept to manage. This is one of the reasons I like Java, because the programmer doesn't need to worry about the pointer of an object.
Like @jarnbjo says, you can check, if some references are similar, with a syntax like this:
Note that
==
checks the equality of reference address. If you want to check the equality of the value of the strings, use theequals()
method.I suggest you to read this SO question, this Wikipedia page and this page.
No, you cannot. Even using the Java Native Interface (JNI), you can only get an opaque handle to the data structure, not a pointer to the real JVM object.
Why would you want such a thing? It wouldn't necessarily be in a form you could use for anything, anyway, even from native code.
Actually address can be obtained with sun.misc.Unsafe but it is really very unsafe. GC often moves objects.