The instanceof operator ensures that the left operand is an instance of the right operand or a subclass of it. On the other hand Class.isAssignableFrom() method, as the name suggests, indicates whether an instance of the class, passed as parameter to this method, can be assigned to the reference variable of type indicated by the class on which this method is called. Thus the statement
x instanceof Y
x.getClass().isAssignableFrom(Y.class)
Consider a hierarchy of 3 classes A, B and C where C extends B and B extends A. Also consider a statement:
B b = new C();
Now the statement
b instanceof A
will return true as b (which is actually an instance of Class C) is an instance of subclass of A. similarly statements
b instanceof B
b instanceof C
will also return true for the same reason. But note that if b would be an instance of Class B (i.e. the above expression would be B b = new B()), the last statement i.e. b instanceof C would have returned false as instance of B is neither C nor a subclass of C.
Now consider the statement:
b.getClass().isAssignableFrom(A.class)
This actually means: can an instance of class A be assigned to reference type of C (note that b.getClass() is C class no B)? In syntactical way, this means: can we write C c = new A()? And we know this is not true. Thus the above statement will return false. Similarly for the statement b.getClass().isAssignableFrom(B.class) will also return false because C c = new B() is incorrect. But the statement
b.getClass().isAssignableFrom(C.class)
will return true as C c = new C() is a correct statement.
I hope this concised explanation will make the difference very clear.
1 comment:
Very useful one.First time came to know about isAssignableFrom()
Post a Comment