IsAssignableFrom does not return true for subclass

So, I want to check if it is possible to assign a class to a superclass that contains many subclasses, something like this

public class A { public A(){ } } public class B extends A { public B(){ } } public class C extends B { public C(){ } } public static void main() { A a = new C(); boolean whyAmIFalse = a.getClass().isAssignableFrom(B.class); } 

Why does this return false? Obviously, it can be assigned to class B as

 B b = (B)a 

does not return an error, so why does it return false. Isn't that a function that she describes as? Is there a function that does what I want for me (i.e., I am that class or subclass)?

+7
source share
3 answers

If what you want to do is to check if a actual type B or a subtype, you got it back: this

  B.class.isAssignableFrom(a.getClass()); 
+14
source

This is because getClass() returns the actual class, not the declared class of the variable - a.getClass() returns the class C (C.class), which is the actual class of the object that was assigned to the variable A a , and you really cannot assign B a C

http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#getClass ()

+5
source

Since class B does not extend / implement class C, this is what isAssignableFrom () criterion is. An instance of class B may be an instance of class C according to your example. To verify this, use "instanceof".

0
source

All Articles