开发者

cast primitive array to Object and back

I have this

int [] abc = new int[30];

Object arr = abc;

How do i cast arr back to int[] ?? ie

int [] foo = (int[])arr

Also, if arr could point to int[] or byte[], how to distinguish them??

I've checked arr.getClass().getName() returns [I and arr.getClass().isPrimitive() is false. Must be another way to detect it?

Thanks.

PS. I mus开发者_JS百科t use primitive types in my arrays.


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) {
    ...
}

or better

if(arr instanceof int[]) {
   ...
}

The [I class name is another way, but less clear in code. You could also do arr.getClass().getComponentType(), which should return int.class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜