如果未定义toString,则
Java使用一些哈希打印类名.如果定义了toString,如何实现此功能?
package tests.java.lang; public class Try_ToString { public static class MyClass { protected int value; public MyClass(int value) { this.value = value; } } public static class MyClass2 extends MyClass { public MyClass2(int value) { super(value); } @Override public String toString() { return String.valueOf(value); } } public static void main(String[] args) { MyClass a = new MyClass(12); MyClass b = new MyClass2(12); System.out.println("a = " + a.toString()); System.out.println("b = " + b.toString()); } }
解决方法
默认的toString实现只是将对象的类名“@”与其十六进制的hashCode连接起来.
public static String defaultToString(Object o) { return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); }