检测对象是否已重写toString() [英] Detect if object has overriden toString()

查看:87
本文介绍了检测对象是否已重写toString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个对象,需要对其进行记录.他们中有些人习惯使用toString(),然后我想使用它,但有些人没有,我得到类似mightypork.rogue.bus.events.MouseMotionEvent@2d19587d的东西.

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.

我正在寻找一种动态(也许具有反射性)检查传入对象是否具有toString()自身的方法.

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

}

旁注:

这是一个事件总线系统,某些类可以预订并接收基于已实现接口的事件.我可能无法要求所有客户端都具有toString(),而且我想将此方法用于多个目的.

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.

推荐答案

如果使用Object getClass()方法,则可以使用该类并调用getMethod().getDeclaringClass()方法.如果它是Object,则不会被覆盖.否则,将忽略沿该行的某个位置. 来源

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

这篇关于检测对象是否已重写toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆