• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cast Object to int[]  RSS feed

 
Lenkwe Makhubela
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to cast an Object to a primitive integer array? Like having a defined "objValue" as of type Object then trying to do the following:
int []arr = (int[])objValue;
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Yes, it's possible, but only if the object actually is an int[]. In other words, this is legal:

Object o = new int[5];
int[] ia = (int[]) o;

When casting object references, the cast never makes any change to the object itself; it's only an instruction to the compiler to treat the object as a different type. If the object is not actually of the correct type, you'll get a ClassCastException at runtime.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fortunately you can check for that:

There is even a Class object for that: int[].class
 
Lenkwe Makhubela
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Ernest!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!