Search code examples
javareflectionwrapperprimitive

Converting an array of wrappers to an array of primitives


If I have an array of instances of primitive wrapper classes, how can I obtain an array of their respective primitives?

Object toPrimitiveArray(Object[] wrappedArray) {
    return ?;
}

Object primitiveArray = toPrimitiveArray(new Integer[] { 1, 2, 3 });

In the above example, I'd like toPrimitiveArray() to return an int[] containing the int values 1, 2, and 3.


Solution

  • The problem is that your method cannot know what type of Number is being contained by the array, because you have defined it only as an array of Object, with no further information. So it's not possible to automatically produce a primitive array without losing compile-time type safety.

    You could use reflection to check the Object type:

    if(obj instanceof Integer) {
        //run through array and cast to int
    } else if (obj instanceof Long) {
        //run through array and cast to long
    } // and so on . . .
    

    However, this is ugly and does not allow the compiler to check for type safety in your code, so increases the chance of error.

    Could you switch to using a List of Number objects instead of an array? Then you could use type parameters (generics) to guarantee type safety.