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()"?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

if array is MyObject[] can't cast value to Object[]
@nir: Yes you can. Did you try it? See docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.10.3 I'll edit an example into the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.