Java是否具有“是一种类”?测试方法 [英] Does Java have an "is kind of class" test method

查看:120
本文介绍了Java是否具有“是一种类”?测试方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆