Does Java have an "is kind of class" test method

if(object instanceof WhereStatement) {
   WhereStatement where = (WhereStatement) object;
   doSomething(where);
}

Note that code like this usually means that your base class is missing a polymorphic method. i.e. doSomething() should be a method of Statement, possibly abstract, that is overridden by sub-classes.


The answer to your question is instanceof.

However, keep in mind that if your code needs instanceof, it's a sign that something is not right with your design. There are some cases when instanceof is justified, but they are rather exceptions. Usually, if your subclasses need to behave differently, you have to use polymorphism instead of if()s.


if (obj.getClass().isInstance(Statement.class)) {
   doStuffWithStatements((Statement) obj));
}

The nice thing about this technique (as opposed to the "instanceof" keyword) is that you can pass the test-class around as an object. But, yeah, other than that, it's identical to "instanceof".

NOTE: I've deliberately avoided editorializing about whether or not type-instance-checking is the right thing to do. Yeah, in most cases, it's better to use polymorphism. But that's not what the OP asked, and I'm just answering his question.


Try this:

if (Statement.class.isInstance(obj)) {
    doStuffWithStatements((Statement) obj));
}

since Class.isInstance() method takes an object instance as a parameter.