views:

304

answers:

3

Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:

if(obj is MyType)

Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null.

I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?

Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.

+16  A: 
if (objectReference instanceof type)

More info here: http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm

nickf
oh yes, that's exactly what I was looking for. Thanks.
+1  A: 

obj instanceof TargetType returns true just in case TargetType is in the type hierarchy that contains obj.

See Sun's tutorial

Alan
+6  A: 

You can only use instanceof with a class literal: that is:

Class type = String.class;

if (myObj instanceof String) // will compile

if (myObj instanceof type) //will not compile

The alternative is to use the method Class.isInstance

if (type.isInstance(myObj)) // will compile
oxbow_lakes