开发者

cast primitive array to Object and back

开发者 https://www.devze.com 2023-02-16 08:24 出处:网络
I have this int [] abc = new int[30]; Object arr = abc; How do i cast arr back to int[] ?? ie int [] foo = (int[])arr

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

精彩评论

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