Detect if object overridden toString ()

I get an object and need to register it. Some of them have cusom toString(), and then I would like to use this, but some do not, and I get something like mightypork.rogue.bus.events.MouseMotionEvent@2d19587d.

I'm looking for a way to dynamically (perhaps with reflection?) Verify that the incoming object is toString()redefined itself.

String objToString(Object o)
{
    if(???) {
        return o.toString();
    } else {
        // fallback method
        return o.getClass().getSimpleName();
    }

}

Side note:

This is an event bus system, some classes can subscribe and then receive events based on implemented interfaces. I cannot require all clients to have toString (), plus I want to use this method for more than one purpose.

+4
source share
4 answers

Object getClass(), getMethod().getDeclaringClass(). Object, . , - , .

+13

, , toString :

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TemplateHelper {

    public static void main(String [] args){
        int a = 3;
        try {
            objToString(a);
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void objToString(Object object) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException{
        Class c = object.getClass();
        Method[] methods = c.getMethods();
        for (Method method : methods) {
            if(method.getName().equals("toString")){
                System.out.println(method.getName()); //THERE IS toString in object
                break;
            }
        }
    }

}
+1

, , :

    String objToString(Object o)
{
    if(!(o.toString().contains("@" + o.hashCode()))) {
        return o.toString();
    } else {
        // fallback method
        return o.getClass().getSimpleName();
    }

}

- :

String objToString(Object o) {
  if (o.toString().equals(
      o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()))) {
    // fallback method
    return o.getClass().getSimpleName();
  } else {
    return o.toString();
  }
}
0

Here's how you can use reflection to figure it out. Find the method toStringin the object that you obtained with reflection. If it was declared in java.lang.Object, use your own method.

import java.lang.reflect.Method;
import java.util.Random;

public class ToStringUtils {
    public static String myToString(Object o) {
        if (o == null)
            return "null";
        if (overridesToString(o.getClass()))
            return o.toString();
        // Replacement for Object.toString()
        return o.getClass().getSimpleName() + "@" + System.identityHashCode(o);
    }

    public static boolean overridesToString(Class<?> clazz) {
        Method m;
        try {
            m = clazz.getMethod("toString");
        } catch (NoSuchMethodException e) {
            // Can't be thrown since every class has a toString method through Object
            return false;
        }
        return (m.getDeclaringClass() != Object.class);
    }

    // Small demo
    public static void main(String[] args) {
        System.out.println(myToString(new Integer(5)));
        System.out.println(myToString(new Random()));
    }
}
0
source

Source: https://habr.com/ru/post/1535056/


All Articles