开发者

variables reference value of string

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开发者_C百科 value inside t

but for string? maybe with method hashCode()??


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.


From the API:

Object.toString(): The toString method for class 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.


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


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


The overloaded String.valueOf( t ) is another way of doing this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜