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)?
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());
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With