views:

114

answers:

2

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 and 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;
}
+2  A: 

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.

Yishai
I was praying to the holy god of programming that this could be avoided, and StackOverflow was my last resort. I will perform this abomination now, but know that my soul is proffered to the depths of hell along with the coming committal. Peace upon you, brother. *salute*
Jordan
Dramatics aside, why does this bother you so much? 10 lines of extra code is enough to make you feel you've lost your innocence? That primitives are not objects is a core reality in Java. If this bothers you that much, well, get over it or choose another language.
Mark Peters
It mostly bothers me because the code I'm working in has it's fair share of if-else chains 1000 lines long that could have easily been avoided but are now ingrained in the project and I was hoping to avoid adding a link to the chains. I fixed it with a recursive function (to help with nested arrays) similar to what Bozho's library function would have done. I will add this function to my question for reference and critiques.
Jordan
+1  A: 

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.

Bozho
While I cannot import your faithful observance, my task is now to reincarnate the spirit of your suggestion as best as I am allowed by the laws of nature.
Jordan
why you can't import it? download commons-lang, add it to classpath, and you are done
Bozho
@Bozho: Either because Jordan can't use additional libraries or because commons-lang may be incompatible with the version of the JDK that Jordan is using. Are there really that many people still using 1.3?
JAB