我们可以为字符串调用Object类的toString()方法吗
String string = new String("Hello");
System.out.println(string);
对于字符串,将在String中调用重写的方法。有什么方法可以为String调用Object类的toString()方法吗?
我想打印出String对象的内存地址
不,您不能调用重写的方法。但是,你可以模拟输出Object
的toString()
(基本上只使用哈希码)如下:
string.getClass().getName() + "@" + Integer.toHexString(string.hashCode())
* edit:正如Taemyr在评论中所注意到的,一个不使用hashCode
定义的更接近的模仿String
将是:
string.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(string))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句