Java是否具有“是一种类”?测试方法 [英] Does Java have an "is kind of class" test method
问题描述
我有一个基类, Statement
,其他几个类继承,名为 IfStatement
, WhereStatement
等等...在 if
语句中执行测试的最佳方法是什么,以确定哪种 Statement
类实例派生自?
I have a baseclass, Statement
, which several other classes inherit from, named IfStatement
, WhereStatement
, etc... What is the best way to perform a test in an if
statement to determine which sort of Statement
class an instance is derived from?
推荐答案
if (obj.getClass().isInstance(Statement.class)) {
doStuffWithStatements((Statement) obj));
}
关于这种技术的好处(而不是instanceof关键字)是你可以将测试类作为对象传递。但是,是的,除此之外,它与instanceof相同。
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".
注意:我故意避免编辑类型实例检查是否是正确的要做的事情。是的,在大多数情况下,最好使用多态。但这不是OP所要求的,我只是在回答他的问题。
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.
这篇关于Java是否具有“是一种类”?测试方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!