Reputation: 31
What is the equivalent of this without using instanceof? Maybe something more simple while using true, false or else statements?
public static void p (Object...ar)
{
for (int i=0; i < ar.length; i++)
{
if (ar[i] instanceof int[])
{
Upvotes: 1
Views: 2565
Reputation: 135762
For primitive arrays you can, instead of:
if (ar[i] instanceof int[])
Use:
if (ar[i].getClass() == int[].class)
Note:
The above code works fine for arrays of primitive types. Please be aware, though, that instanceof
also checks if the object in the left-part is a subtype of the class in the right-part, while ==
does not.
For objects, the equivalent to (myInstance instanceof MyClass[])
(checks for subtyping) is:
( MyClass[].class.isAssignableFrom( myInstance.getClass() ) )
Upvotes: 5
Reputation: 333
use isAssignableFrom
public static void test(Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i].getClass().isAssignableFrom(int[].class)) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
you can use isAssignableFrom in a dynamic way too, see this post to know the difference between instanceof and isAssignableFrom What is the difference between instanceof and Class.isAssignableFrom(...)?
Upvotes: 0
Reputation: 2610
Class<?> intArrayCls = int[].class;
...
if (intArrayCls.isInstance(ar[i])) {
Would do the trick too.
JavaDoc of isInstance. It is a little more flexible as it doesn't just test equality like the accepted answer.
Upvotes: 0
Reputation: 2079
You could use:
(getClass().isArray())
and checking if integer array:
ar.getClass().toString().equals("class [I")
updated:
if(ar.getClass().isArray()) {
if(ar[i].getClass() == int[].class)
....
else if(ar[i].getClass() == String[].class)
....
}
Upvotes: 1
Reputation: 15729
Check out java.lang.Class, which has a method isAssignableFrom(Class<?> cls)
For your specific example with arrays, it also has isArray()
and getComponentType()
Upvotes: 0
Reputation: 97571
Another option would be to just assume it is an int[]
, and catch the resulting exception if it is not:
public static void p (Object...ar)
{
for (int i=0; i < ar.length; i++)
{
int[] i_arr;
try {
i_arr = (int[]) ar[i];
} catch (ClassCastException e) {
continue;
}
//...
Upvotes: 1
Reputation: 1365
Generally, inheritance and polymorphism is a better solution to your problem. Rather than check what kind of object you are dealing with, have several classes inherit from a generic class, and call the shared methods.
Upvotes: 0