Cast primitive type array into object array in java

In Java, primitive types and reference types are two distinct worlds. This reflects to arrays: A primitive array is not an object array, that's why you can't cast.

Here is a simpler version of your solution in the question:

private Object[] getArray(Object val){
    if (val instanceof Object[])
       return (Object[])val;
    int arrlength = Array.getLength(val);
    Object[] outputArray = new Object[arrlength];
    for(int i = 0; i < arrlength; ++i){
       outputArray[i] = Array.get(val, i);
    }
    return outputArray;
}

This will still work when they sometimes decide to add new primitive types to the VM.

Of course, you might want to do the copying always, not only in the primitive case, then it gets even simpler:

private Object[] getArray(Object val){
    int arrlength = Array.getLength(val);
    Object[] outputArray = new Object[arrlength];
    for(int i = 0; i < arrlength; ++i){
       outputArray[i] = Array.get(val, i);
    }
    return outputArray;
}

Of course, this is not casting, but converting.


Here is a simple one-liner:

Double[] objects = ArrayUtils.toObject(primitives);

You will need to import Apache commons-lang3:

import org.apache.commons.lang3.ArrayUtils;