How do I check if an object given to me is an int[]
in Java?
views:
330answers:
4
+22
A:
The way you'd expect:
if (theObject instanceof int[]) {
// use it!
}
Arrays are Objects
, even if they're arrays of primitives.
Michael Myers
2009-04-23 19:18:31
Yep. That's the way to do it. I knew there was a better way than my answer.
MBCook
2009-04-23 19:22:11
A:
Get the runtime class of the variable if its a single dimension array the class name is like [int if it is a 2 dimensional array the class name is [[int and if it's a 3 dimensional class name is [[[int
if ( j.class.Name.equals("[int")) {
......
}
S M Kamran
2009-04-23 19:23:58
Reflection would also work, but the question didn't mention multidimensional arrays.
Michael Myers
2009-04-23 19:25:43
j.class would work in Java 6 as well and if it's not then the point is however communicated well. However the instanceof would be better because I think it's deduced at compile time with out a call to a class method. However for the sake of providing a different proposition I'm adding this.
S M Kamran
2009-04-23 19:32:03
I downloaded Java 6 specifically to test this, and it doesn't seem to work. "class" does not seem to be a member accessible from an instance, at least not in JDK1.6.0_13
skiphoppy
2009-04-23 21:15:50
A:
intanceof is simplest but to do literally what you ask.
if (o.getClass() == int[].class)
Peter Lawrey
2009-04-23 19:39:42
important to note: instanceof will not throw a NullPointerException if o is null, but this will
Kip
2009-04-23 19:49:39