Please explain the differences between instanceof and isInstance(Object obj).

Amir Pashazadeh

First difference:
instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.

Other differences:
you could use instanceof on types (which are known on compile time), and isInstance() could only be called on an instance of 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!

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact