Objects.deepToString(Object o)方法 [英] Objects.deepToString(Object o) method

查看:103
本文介绍了Objects.deepToString(Object o)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.Objects包含deepEquals(Object a, Object b)方法,该方法可用于比较任何类型的对象(包括数组和空引用),但不包含类似的deepToString(Object o).这真令人失望. (顺便说一句,此类的私有构造函数包含消息没有适合您的java.util.Objects实例!" ,从某种程度上解释了为什么此类如此含义).在这种情况下,我尝试自己实现该方法:

The class java.util.Objects contains the deepEquals(Object a, Object b) method that can be used to compare objects of any type (including arrays and null references), but doesn't contain a similar deepToString(Object o). This is disappointing. (By the way, the private constructor of this class contains the message "No java.util.Objects instances for you!" that explains to some extent why this class is so mean). That being the case, I've tried to implement the method myself:

public static String deepToString(Object o) {
    if (o == null || !o.getClass().isArray())
        return Objects.toString(o);
    else
        return Arrays.deepToString((Object[])o);
}

问题在于它不适用于基本类型的一维数组.我是否必须遍历所有带有嵌套else if的原始数组类型,并为它们调用相应的Arrays.toString(...)方法,还是有一个更简单的替代方法?

The problem is that it doesn't work with one-dimensional arrays of primitive types. Do I have to go through all primitive array types with nested else ifs and call corresponding Arrays.toString(...) methods for them, or there is a simpler alternative?

推荐答案

我来到了这个解决方案:将原始数组包装到Object[]中,并从公共Arrays.deepToString(Object[] a)返回的结果中删除外括号:

I came to this solution: wrap a primitive array into Object[] and remove the outer brackets from the result returned by the public Arrays.deepToString(Object[] a):

public static String deepToString(Object o) {
    if (o == null || !o.getClass().isArray())
        return Objects.toString(o);
    else if (o instanceof Object[])
        return Arrays.deepToString((Object[])o);
    else {
        String s = Arrays.deepToString(new Object[] { o });
        return s.substring(1, s.length() - 1);
    }
}

效率不高,因为它可以创建两个大字符串,而不是单个字符串.但是有了这个技巧,我可以使用隐藏的

Not very efficient, because it could create two large strings instead of a single one. But with this trick, I can use the hidden

Arrays.deepToString(Object[] a, StringBuilder buf, Set<Object[]> dejaVu)

包含原始数组解析逻辑的方法.

method that contains the primitive arrays parsing logic.

这篇关于Objects.deepToString(Object o)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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