How can I get the reference value of a string object?
If I hava a class like
class T()
{
}
T t = new T();
System.out.println( t);
print out T@a3455467 that is the reference value inside t
but for string? maybe with method hashCode()??
How can I get the reference value of a string object?
If I hava a class like
class T()
{
}
T t = new T();
System.out.println( t);
print out T@a3455467 that is the reference value inside t
but for string? maybe with method hashCode()??
print out T@a3455467 that is the reference value inside t
No, that is not the reference value of t
, that is simply the value returned by Object.toString
for the object referred to by t
. (The implementation of the println
-method calls the toString
method on the given argument.)
If you have say,
String s = "hello world";
then the reference to the string is stored in s
. There is no way in Java (as there is in C/C++) to get hold of the "address" of the string (or the value of s
).
From the API:
Object.toString()
: ThetoString
method forclass Object
returns a string consisting of the name of the class of which the object is an instance, the at-sign character@
, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
So yes, it's simply Integer.toHexString(someString.hashCode())
that you want.
That said, this is not "the reference value of an object". It's just, as it says, the hash code of the object in hexadecimal. Different instances of String
which are equals
would have the same hashCode()
, as per the contract. This would also apply to other types as well.
The overloaded String.valueOf( t )
is another way of doing this.
What you want is the systems identity hash. You can get it by:
int id = System.identityHashCode(t);
The default implementation of Object.toString()
is:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
The default implementation of Object.hashCode()
is System.identityHashCode()
.
But also the systems identity hash code just garantees to be constant for the same instance (not even unique yet). That need not to be the reference value - whatever this will be in the jvm implementation. The real reference value is opaque, not really offered to the public in java. You cannot transform it to a hex address and have a look into memory or something like that.
If you mean Reference Value in the sense of Memory Address of an object, this is meaningless in Java. The memory address of an object can change at any time in the age of copying garbage collectors. Furthermore the size of an address depends on JVM host platform/implementation (32/64 bit, possibly even more in future).