Does Java have an “is kind of class” test method

后端 未结 6 1825
我寻月下人不归
我寻月下人不归 2021-02-03 22:01

I have a baseclass, Statement, which several other classes inherit from, named IfStatement, WhereStatement, etc... What is the best way t

6条回答
  •  [愿得一人]
    2021-02-03 22:25

    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.

提交回复
热议问题