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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With