Reputation: 48817
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
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
Reputation: 12347
You can use java.lang.reflect.Array.get()
to get a specific element from your unknown array.
Upvotes: 7
Reputation: 20254
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.
Upvotes: 5
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