Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Object to Array

Tags:

java

arrays

So I have an Object which MIGHT be an array. It can also be primitive, or a string. If it is an array, it can be an array of literally anything.

I have no problem figuring out if it is an array but I can't seem to cast it into anything that I can iterate through to get the values out of.

// o is an object and clazz is the class of the o
if (clazz == Array.class) {
            Class ofArray = o.getClass().getComponentType();
            String arrayType = ofArray.getName(); // 'Double' for my test case
            //ERROR: [D cannot be cast to [Ljava.lang.Object 
            Object[] objects = (Object[]) o; 
    }

My background is in ruby and php (where it would just work) and the static typing is messing with my head. Any ideas?

EDIT:

This throws the error

[D cannot be cast to [Ljava.lang.Object.

What am I missing?

if (o.getClass().isArray()) {
    Object[] objects = (Object[]) o;  
}
like image 786
Ryan Epp Avatar asked May 07 '13 19:05

Ryan Epp


People also ask

Can I cast an object to array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

Can we convert object to array in java?

toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.

How do you create an array of objects?

An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.


2 Answers

If you do not want to make the switch for all primitive types you could do like this:

if (ofArray.isPrimitive()) {
    int length = Array.getLength(o);
    for (int i = 0; i < length; i++) {
        Object obj = Array.get(o, i);
        System.out.println(obj);
    }
}
else {
    Object[] objects = (Object[]) o;
    for (Object obj : objects) {
        System.out.println(obj);
    }
}

Edit: If you don't want to loop in two different places in your code use this method to convert the primitive arrays to an object array:

static Object[] convertToObjectArray(Object array) {
    Class ofArray = array.getClass().getComponentType();
    if (ofArray.isPrimitive()) {
        List ar = new ArrayList();
        int length = Array.getLength(array);
        for (int i = 0; i < length; i++) {
            ar.add(Array.get(array, i));
        }
        return ar.toArray();
    }
    else {
        return (Object[]) array;
    }
}
like image 170
Vegard Avatar answered Oct 01 '22 13:10

Vegard


This will work for arrays with elements that are sublcasses of Object:

if (clazz.isArray()) {
    Object[] objects = (Object[]) o;
    for (Object obj : objects)
        System.out.println(obj);
}   

If you need to cast the array to an specific array type you could (ab)use instanceof but for, say, just printing the contents as strings, an Object[] suffices.

UPDATE

If the array is of primitive types, you have no option but to test for each one and cast to the correct type, Object[] won't work for this case - but there aren't that many primitive types in Java, so it won't be a gigantic switch :) . This is what I mean:

if (clazz.isArray()) {
    if (clazz.getComponentType().equals(double.class)) {
        double[] numbers = (double[]) o;
        for (double d : numbers)
            System.out.println(d);
    }
}  
like image 33
Óscar López Avatar answered Oct 01 '22 12:10

Óscar López