Java中最简单的实现“is”的方法是什么?

6

许多编程语言都有检查对象是否属于某个类型(包括父类的子类)的功能,使用“is”实现,如下所示:

if(obj is MyType)

或者稍微麻烦一些,您可以使用“as”关键字进行软类型转换,并查看结果是否为空来检查其他语言。多年来我没有使用过Java,现在我正在重新学习它,但Java肯定有一种简单的方法可以轻松地完成这项工作,而不必深入研究Reflection API吧?
感谢您提前回答。我已经在这里和其他地方搜索过了,但涉及的关键词太通用了,即使我确定这有一个简单的答案,但通过Google搜索它也很困难。
3个回答

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

更多信息在这里


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

1

obj instanceof TargetType 只有在包含 obj 的类型层次结构中包含 TargetType 时才返回 true。

请参见 Sun's tutorial


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接