java - 如何在 Java 中的对象上强制调用父类(super class)实现 Object.toString() 而不是子类重写实现

标签 java overriding superclass subclassing

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>"

我需要的是调用testobj1toString()实际执行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 覆盖类,因此它正在执行 StringhashCode() ,不是ObjecthashCode() .

是否可以调用被重写的方法,而不是重写的方法?

Please note: The use of String class is merely an example. Do not base your answer on the assumption that the object is always a String 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 like String, 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/

相关文章:

java - 我如何知道 javax.jnlp.PrintService 何时完成打印我的 Printable 对象

java - 使用 rx-java2 : get first error 进行验证

java - 在 ASync 类中覆盖和重写

c - 重写 C 中的函数调用

python - 为什么我的父类(super class)调用我的子类方法?

java - C1.bar()执行了,不应该是C2.bar吗?

java - 如何在Java中高效存储滚动播放项属性?

Java Azure AD OpenId 连接提供 302 重定向代码

css - 覆盖 div 的页面宽度

java - 为什么父类(super class)分配给子类会出错?