Pregunta

If toString is not defined, then Java prints class name with some hash. How to reach this functionality if toString is defined?

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());

    }
}
¿Fue útil?

Solución 2

The default toString implementation just concatenates the object's class name, "@", and its hashCode in hexadecimal.

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

Otros consejos

The answer from @immibis is correct, however it wouldn't work if your class override the hashcode method. But you can use 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));
}

The docs tell the how the implementation works.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

You could just do that, or put it in a (static?) method.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top