Passing 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 should not know what type of parameter is oin method. How can I pass it to an array Object[]?

instanceof cannot be a solution, since a parameter can be an array of any type.

PS: I saw several questions about SO dedicated to casting an array, but no one (yet?) Where you don't know the type of array.

+5
source share
4 answers

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

+6
source

You cannot pass an array of primitives ( intin 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 };

he should work.

+5
source

Object[], int -s. , , :

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

1

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

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 which type of array it is and send to it when necessary.

+3
source

All Articles