简体   繁体   中英

The equivalent of instanceof

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[])
                {

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()  )   )

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)
            ....
}

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;
        }
        //...

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.

Check out java.lang.Class, which has a method isAssignableFrom(Class<?> cls)

For your specific example with arrays, it also has isArray() and getComponentType()

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.

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(...)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM