How do I print an array that has been converted to object?

114 Views Asked by At

I've got a logger which accepts object as input, and it is rather convenient for me. But now I've got to log an input which is of type int[]. I want to modify the method so it properly logs any array or Iterable.

In c#, what I would do is this:

int[]data=new int[10];
object tmp=data;

.....

if (tmp is IEnumerable)
{
     StringBuilder _tmp = new StringBuilder();
     foreach (var i in (IEnumerable)tmp)
     {
         if (_tmp.Length > 0)
         {
             _tmp.Append(",");
         }
         _tmp.Append(i);
     }
     var r = _tmp.ToString(); 
 }

I've tried checking int[] against Iterable (it's not), than I tried checking with tmp.getClass().isArray(), which works, but now I have trouble enumerating the members of that array. I need a method that will work with any array or list of objects.

How do I properly do this in Java?

2

There are 2 best solutions below

0
On BEST ANSWER

You could use the methods in java.lang.reflect.Array like

Object obj = new int[] { 1, 2, 3, 4 };
try {
    int len = Array.getLength(obj);
    for (int i = 0; i < len; i++) {
        if (i != 0) {
            System.out.print(", ");
        }
        System.out.print(Array.get(obj, i));
    }
    System.out.println();
} catch (IllegalArgumentException iae) {
    iae.printStackTrace();
}

Output is

1, 2, 3, 4

0
On

There is probably no clean way to do this in Java (*). I think this will work:

Object tmp = ...;

String s;
if (tmp instanceof boolean[]) {
    s = Arrays.toString((boolean[]) tmp);
}
else if (tmp instanceof byte[]) {
    s = Arrays.toString((byte[]) tmp);
}
else ...

and do the same for char[], double[], float[], int[], long[], short[]; if isArray() is true and it's not any of the above cases,

s = Arrays.toString((Object[]) tmp);

EDIT: I've tested this and it works.

See this javadoc for a list of the available Arrays.toString methods.

(*) OK, using Array.get as in the other answer is a cleaner approach, probably. I've tested that and it works too.