sp0*_*00m 6 java arrays reflection casting
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我不应该知道什么是该参数的类型o
中method
.我怎么能把它投射到Object[]
数组中?
instanceof
因为参数可以是任何类型的数组,所以不能成为解决方案.
PS:我已经看过几个关于SO处理数组转换的问题,但没有人(还有?)你不知道数组的类型.
您不能将基本数组(int
在您的情况下为Object
s )转换为s 数组.如果你改变:
int[] a = new int[] { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
至
Integer[] a = new Integer[] { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
它应该工作.