Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isAssignableFrom doesn't return true for sub-class

So I want to check to see if a class is assignable to a super class that contains many sub classes, 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 is this returning false. Is it not the function it describes itself as? Is there a function that does accomplish what I want it to me (ie I am that class or a subclass of it)?

like image 475
Kevin DiTraglia Avatar asked Sep 20 '12 23:09

Kevin DiTraglia


2 Answers

If what you want to do is test whether or not a's actual type is B or a subtype, you've got it backwards: it's

 B.class.isAssignableFrom(a.getClass());
like image 93
Louis Wasserman Avatar answered Sep 19 '22 06:09

Louis Wasserman


This is because getClass() returns the actual class, not the declared class of a variable -- a.getClass() will return the class C (C.class), which is the actual class of the object that was assigned to the variable A a and you indeed can't assign a B to a C

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

like image 38
Stephen P Avatar answered Sep 20 '22 06:09

Stephen P