Search code examples
javatypechecking

What is the easiest way to do 'is' in Java?


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.


Solution

  • if (objectReference instanceof type){
        //Your code goes here
    }
    

    More info here.