Please note: I am not asking how to force all classes to override
toString()
in their source code. Please read the question carefully.
java中的所有类都扩展Object
类(class)。如果任何类(class)有 toString()
覆盖,调用 Object.toString()
实际上会执行重写方法。
例如:
String test = "StackOverflow";
Object testobj1 = (Object) test;
System.out.println(testobj1.toString()); // prints "StackOverflow"
Object testobj2 = new Object();
System.out.println(testobj2.toString()); // prints "java.lang.Object@<Object.hashcode() in hex>"
我需要的是调用testobj1
的toString()
实际执行Object
类(class)toString()
方法。像这样的东西:
System.out.println( [[testobj1 as Object]] .toString()); // prints "java.lang.String@<Object.hashcode() in hex>"
我尝试使用:
System.out.println(testobj1.getClass().getName() + '@' + Integer.toHexString(testobj1.hashCode()));
但这也有和上面一样的问题。 hashCode()
方法也被 String
覆盖类,因此它正在执行 String
的hashCode()
,不是Object
的hashCode()
.
是否可以调用被重写的方法,而不是重写的方法?
Please note: The use of
String
class is merely an example. Do not base your answer on the assumption that the object is always aString
object.Also assume: I have no access to the source code of classes, so I can't just remove
toString()
implementation from them or do things like creating an abstract class. This has to work for any object (including that of Java's own classes or any API likeString
,HashMap
,HttpServlet
, etc). This also means that I'm not looking for answers like these.
最佳答案
您需要使用System.identityHashCode()
来获取实际(原始)哈希码。
试试这个代码:
public static void main(String[] args) {
String test = "StackOverflow";
Object testobj1 = (Object) test;
System.out.println(testobj1.toString()); // prints "StackOverflow"
System.out.println(testobj1.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(testobj1)));
System.out.println(test.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(test)));
Object testobj2 = new Object();
System.out.println(testobj2.toString());
System.out.println(testobj2.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(testobj2)));
}
输出:
StackOverflow
java.lang.String@5d888759
java.lang.String@5d888759
java.lang.Object@2e6e1408
java.lang.Object@2e6e1408
关于java - 如何在 Java 中的对象上强制调用父类(super class)实现 Object.toString() 而不是子类重写实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27438308/