Saideira
Saideira

Reputation: 2434

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 must use primitive types in my arrays.

Upvotes: 3

Views: 3680

Answers (1)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

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.

Upvotes: 6

Related Questions