将原始数组转换为Object并返回 [英] cast primitive array to Object and back
问题描述
我有这个
int [] abc = new int[30];
Object arr = abc;
如何将 arr
投射回 int []
?即
int [] foo = (int[])arr
此外,如果arr可以指向 int []
或 byte []
,如何区分它们?
Also, if arr could point to int[]
or byte[]
, how to distinguish them??
我检查了 arr.getClass()。getName()
返回 [I
和 arr.getClass()。isPrimitive()
返回 false
。
I've checked arr.getClass().getName()
returns [I
and arr.getClass().isPrimitive()
is false
. Must be another way to detect it?
谢谢。
PS。我必须在数组中使用基本类型。
PS. I must use primitive types in my arrays.
推荐答案
强制转换正确,(int []) arr
可以解决问题。
The casting is right, (int[])arr
does the trick.
如果需要,可以通过比较类对象来识别类型:
You can recognize the type by comparing the class objects, if you want:
if(arr.getClasS() == int[].class) {
...
}
或更佳
if(arr instanceof int[]) {
...
}
[I
类名是另一种方法,但是代码不太清楚。
您也可以执行 arr.getClass()。getComponentType()
,它应该返回 int.class
The [I
class name is another way, but less clear in code.
You could also do arr.getClass().getComponentType()
, which should return int.class
.
这篇关于将原始数组转换为Object并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!