Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 437
sp00m Avatar asked Apr 11 '13 12:04

sp00m


4 Answers

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

like image 147
jabal Avatar answered Sep 18 '22 12:09

jabal


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.

like image 36
codebox Avatar answered Sep 21 '22 12:09

codebox


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;
        // ....
    }
}
like image 20
Andremoniy Avatar answered Sep 22 '22 12:09

Andremoniy


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.

like image 27
CloudyMarble Avatar answered Sep 20 '22 12:09

CloudyMarble