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.
You can use java.lang.reflect.Array.get()
to get a specific element from your unknown array.
You can't cast an array of primitives (int
s in your case) to an array of Object
s. If you change:
int[] a = new int[] { 1, 2, 3 };
to
Integer[] a = new Integer[] { 1, 2, 3 };
it should work.
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;
// ....
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With