Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if object has overriden toString() [duplicate]

I'm receiving an Object and need to log it. Some of them have cusom toString() and then I'd like to use that, but some have none and I get something like mightypork.rogue.bus.events.MouseMotionEvent@2d19587d.

I'm looking for a way to dynamically (perhaps with reflection?) check if the incoming object has toString() overridden itself.

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

}

Side note:

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

like image 396
MightyPork Avatar asked Apr 04 '14 15:04

MightyPork


1 Answers

If you use the Object getClass() method, you can use the class and invoke the getMethod().getDeclaringClass() method. If it is Object, then it is not overridden. Otherwise, somewhere along the line is was overriden. Source

like image 108
nimsson Avatar answered Sep 18 '22 03:09

nimsson