tags:

views:

330

answers:

4

How do I check if an object given to me is an int[] in Java?

+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
Yep. That's the way to do it. I knew there was a better way than my answer.
MBCook
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
Reflection would also work, but the question didn't mention multidimensional arrays.
Michael Myers
That should be j.getClass().getName(), not j.class.Name.
Michael Myers
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
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
+1  A: 
if (o instanceof int[])
{
...
}

Arrays are Objects in java.

Schildmeijer
A: 

intanceof is simplest but to do literally what you ask.

if (o.getClass() == int[].class)
Peter Lawrey
important to note: instanceof will not throw a NullPointerException if o is null, but this will
Kip