Monday, August 6, 2012

instanceof v/s isInstance

instanceof
isInstance()
reserved word
method of java.lang.Class.
Could use instanceof on types (which are known on compile time)
 isInstance() could only be called on an instance for java.lang.Class.
if (obj instanceof MyType) {
...
}


if (MyType.class.isInstance(obj)) {
...
}

so you can have dynamism using isInstane() like this:



   Class x = Integer.class;

   if (x.isInstance(obj)) {
   ...
   }

   x = String.class;

   if (x.isInstance(obj)) {
   ...
   }


as you see you could check the type of an object with an unknown class during compile time!
instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception.
isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class.

No comments:

Post a Comment