instanceof vs isInstance(Object obj)
1 posts in topic
Flat View  Flat View

Posted By:   Ramu_G
Posted On:   Sunday, August 6, 2006 12:24 AM

Please someone help me how to use these two.

what are the differences? it will be better if sample code can be provided.


Re: instanceof vs isInstance(Object obj)

Posted By:   Amir_Pashazadeh  
Posted On:   Tuesday, August 8, 2006 01:41 PM

First difference:

instanceof is a reserved word of Java, but isInstance() 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 fo 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!

About | Sitemap | Contact