Java - Write code to convert Object to String

Requirements

Write code to Convert Object to String

If the object is representing an Array, loop for each element inside the array.

Hint

Use Array.getLength() to get the length of the array typed in Object.

Demo

//package com.book2s;
import java.lang.reflect.Array;

public class Main {
    public static void main(String[] argv) {
        Object array = "book2s.com";
        System.out.println(toString(array));
    }//from  w  w w  .jav a 2s. c  o  m

    private static String toString(Object array) {
        int length = Array.getLength(array);
        if (length == 0) {
            return "[]";
        }

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0;; i++) {
            b.append(Array.get(array, i));
            if (i == length - 1) {
                return b.append(']').toString();
            }
            b.append(", ");
        }
    }
}

Related Exercise