开发者

Pretty print array object, not array of objects?

开发者 https://www.devze.com 2023-01-05 02:57 出处:网络
So, I\'ve already discovered Arrays.toString(arr); So don\'t point me to this question. My problem is just a tiny bit different. In this case, I don\'t have a native array pointer to the array in

So, I've already discovered

Arrays.toString(arr);

So don't point me to this question.

My problem is just a tiny bit different. In this case, I don't have a native array pointer to the array in question. I have it as an Object pointer, and it could be an array of any type (primitive or otherwise). In this case, I can use the above toString() method by casting the Object pointer to Object[]. However, if the pointer is a primitive array, it will throw a runtime exception an开发者_开发问答d crash. So?

Example:

double test[] = {1, 2, 3, 4};
Object t = test;
// Now how do I pretty print t as an array with no access to test?

I solved my problem with this:

public String unkObjectToString(Object o) {
    if(!o.getClass().isArray()) return o.toString();
    int len = Array.getLength(o);
    String ret = "[";
    for(int i = 0; i < len; i++) {
        Object q = Array.get(o, i);
        ret += unkObjectToString(q);
        if(i == len - 1)
            ret += "]";
        else
            ret += ", ";
    }
    return ret;
}


You have to test and cast.

if (o instanceof byte[]) {
      return Arrays.toString((byte[]) o);
} //etc.

You could do this via reflection, but it would not be any cleaner in the end, although it would be a few lines of code less.


ArrayUtils.toString(arrayObj) (commons-lang) - does exactly what you want (also handles multi-dimensional arrays). Simply download the commons-lang jar and add it to your classpath.

0

精彩评论

暂无评论...
验证码 换一张
取 消