6

许多语言都可以检查对象是否属于某种类型(包括父子类),使用“is”实现并像这样使用:

if(obj is MyType)

或者稍微繁琐一点,您可以在其他语言中使用“as”关键字进行软类型转换并查看结果是否为空。

我已经有好几年没用过 Java 了,现在我正在恢复使用它的速度,但是 Java 肯定有一种方法可以轻松地做到这一点,而无需深入研究反射 API?

提前感谢您的回答。我已经在这里和其他地方进行了搜索,但是所涉及的关键字非常通用,即使我确定这有一个简单的答案,谷歌搜索也很困难。

4

3 回答 3

16
if (objectReference instanceof type){
    //Your code goes here
}

更多信息在这里

于 2008-10-26T03:19:11.703 回答
7

您只能instanceof与类文字一起使用:即:

Class type = String.class;

if (myObj instanceof String) // will compile

if (myObj instanceof type) //will not compile

另一种方法是使用该方法Class.isInstance

if (type.isInstance(myObj)) // will compile
于 2008-10-26T13:24:03.243 回答
1

obj instanceof TargetType返回 true 以防万一TargetType在包含 的类型层次结构中obj

参见Sun 的教程

于 2008-10-26T03:22:53.660 回答