sp00m
sp00m

Reputation: 48817

Cast an object to an array

public static void main(String[] args) throws Exception {
    int[] a = new int[] { 1, 2, 3 };
    method(a);
}

public static void method(Object o) {
    if (o != null && o.getClass().isArray()) {
        Object[] a = (Object[]) o;
        // java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
    }
}

I'm not supposed to know what's the type of the parameter o in the method. How can I then cast it in an Object[] array?

instanceof can't be a solution since the parameter can be an array of any type.

PS: I've seen several questions on SO dealing with array casting, but no one (yet?) where you don't know the type of the array.

Upvotes: 6

Views: 1584

Answers (4)

CloudyMarble
CloudyMarble

Reputation: 37566

Option 1

Use o.getClass().getComponentType() to determine what type is it:

if (o != null) {
  Class ofArray = o.getClass().getComponentType(); // returns int  
}

See Demo


Option 2

if (o instanceof int[]) {
  int[] a = (int[]) o;           
}

*Noice: You can use any type other than int to determine what kind of array is it and cast to it when needed.

Upvotes: 3

jabal
jabal

Reputation: 12347

You can use java.lang.reflect.Array.get() to get a specific element from your unknown array.

Upvotes: 7

codebox
codebox

Reputation: 20254

You can't cast an array of primitives (ints in your case) to an array of Objects. If you change:

int[] a = new int[] { 1, 2, 3 };

to

Integer[] a = new Integer[] { 1, 2, 3 };

it should work.

Upvotes: 5

Andremoniy
Andremoniy

Reputation: 34900

You can not cast this object to Object[] class, because actually this is an array of int-s. So, it will be correct if you write:

public static void method(Object o) {
    if (o instanceof int[]) {
        int[] a = (int[]) o;
        // ....
    }
}

Upvotes: 4

Related Questions