0

i want to convert Object to String when the object is an array seen like this

    public void convertValue(Object value) {

    if(value.getClass().isArray()){
        Arrays.deepToString(value.toArray());
    }

}

How i cast value to make "value.toArray()"?

nir
  • 121
  • 2
  • 9

1 Answers1

8

If you only want to handle object arrays (not primitive arrays) you can just cast to Object[], due to array variance:

if (value instanceof Object[]) {
    String text = Arrays.deepToString((Object[]) value);
    ...
}

For primitive arrays you couldn't call deepToString anyway, of course.

Sample code to demonstrate array variance:

public class Test {

    public static void main(String[] args) {
        Object x = new String[] { "Hello", "there" };
        Object[] array = (String[]) x;
        // Prints "class [Ljava.lang.String;"
        System.out.println(array.getClass()); 
    }
}

As you can see, the array value still refers to a string array - but a String[] reference can be assigned to an Object[] variable.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • if array is MyObject[] can't cast value to Object[] – nir Feb 12 '13 at 13:41
  • @nir: Yes you can. Did you try it? See http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.10.3 I'll edit an example into the answer. – Jon Skeet Feb 12 '13 at 13:46