5
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()));
    }
}

Output:

false

Why is it false? Both A.class and a.getClass() should not return the same class!

And in which condition we will get true from the isInstance() method?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Jaikrat
  • 1,124
  • 3
  • 24
  • 45

2 Answers2

13

Because a.getClass() returns Class<A>, but you should pass in an A:

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

If you have two Class instances and want to check for 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
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
3

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

What A.class.isInstance tests is whether the passed object has type A.

missingfaktor
  • 90,905
  • 62
  • 285
  • 365