Friday, September 18, 2009

Instanceof and isAssignableFrom

Java includes the rather handy instanceof keyword that can be used to test if an object is an instance of a particular class. Other methods exist such as Class.isAssignableFrom(Class) and Class.isInstance(Object).

(new Double(100.0) instanceof Double)=true
(new Double(100.0) instanceof Number)=true
(new Double(100.0) instanceof Object)=true
(((Object)new Double(100.0)) instanceof Integer)=false

An alternative (when working with instances of Class)  is to use Class.isAssignableFrom(Class):


i.e. X.isAssignableFrom(Y) is like saying "is Y a kind of X?"

Another alternative (when working with instances of Object) is to use Class.isInstance(Object):

Double.class.isInstance(new Double(100.0))=true
Number.class.isInstance(new Double(100.0))=true
Object.class.isInstance(new Double(100.0))=true
Integer.class.isInstance(new Double(100.0))=false

i.e. X.isInstance(Y) is like saying "is Y a kind of X?"