Instanceof vs isInstance ()

class A{

    public A(){
        System.out.println("in A");
    }
}

public class SampleClass{

    public static void main(String[] args) {
        A a = new A();

        System.out.println(A.class.isInstance(a.getClass()));
    }
}

Conclusion:

false

Why is this a lie? Both A.classand a.getClass()must not return the same class!

And under what condition will we get the true value from the method isInstance()?

+5
source share
2 answers

Because it a.getClass()returns Class<A>, but you must passA :

System.out.println(A.class.isInstance(a));

If you have two instances Classand want to check assignment compatibility, then you need to use isAssignableFrom():

System.out.println(A.class.isAssignableFrom(Object.class)); // false
System.out.println(Object.class.isAssignableFrom(A.class)); // true
+13
source

Because what returns a.getClass()is of type Class<? extends A>, not A.

What tests A.class.isInstance: whether the past object has a type A.

+3
source

All Articles