java - 如何调用 "toString"的默认实现?

标签 java tostring

如果未定义 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());

    }
}

最佳答案

@immibis 的回答是正确的,但是如果你的类重写 hashcode 方法,它就不会工作。但是你可以使用 System.identityHashcode .

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.

public static String defaultToString(Object o) {
     return o.getClass().getName() + "@" + 
            Integer.toHexString(System.identityHashCode(o));
}

关于java - 如何调用 "toString"的默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23468168/

相关文章:

perl - python/ruby的inspect方法中perl的repr等价物是什么

java - Android 在内部类中动态更改按钮背景

javascript - String(number) 是否在内部调用 number.toString?

java - 如果子类没有覆盖被父类(super class)覆盖的字符串,输出是什么?

java - 如何设置分割 PdfPCell 的最小高度

c# - tostring ("000.0") 生成错误值

c# - 双 ToString - 无科学记数法

java - 将真正的字符串整数(例如 "thirty five")转换为整数

java - 什么是上下文对象设计模式?

Java:循环内变量的几种可能类型