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

后端 未结 6 1824
我寻月下人不归
我寻月下人不归 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:15

    This is not the way to do things in an object-oriented way, it's a throwback to the old code/data dichotomy. Now that's not necessarily a bad thing (if you know what you're doing) but it should be left to the non-object-oriented languages like C.

    With proper design, you don't need that sort of behavior. Instead of the construct:

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

    (apologies to benjismith for 'stealing' his code), you should really be making the object itself responsible for its own activities thus:

    obj.doStuff();
    

    Then each different obj class will have its own definition for doStuff. That is the right way to do it.

提交回复
热议问题