Search code examples
javaif-statementinstanceof

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

Solution

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