Cast primitive type array into object array in java

aumanets picture aumanets · Apr 9, 2011 · Viewed 58.8k times · Source

Why I cannot do this in java?

Object[] o = (Object[])(new int[]{0,1,2,3.14,4});

I have a method that receives an object and then represents it as a string, but depending on his type (primitive, primitive wrapper, array, etc...). When I was creating a Unit test, I was passing an array as Object which is Ok, but when I perform cast of that object into Object[] I'm getting ClassCastException. This is only happening with primitive type arrays. Is there any way to avoid this behavior? If not, could someone explain what is the reason of this behavior on Java Virtual Machine.

Any help is very appreciated.

Answer

Datageek picture Datageek · Apr 23, 2015

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;