许多语言都有检查Object是否属于某种类型(包括父类)的工具,使用'is'实现并使用如下:

if(obj is MyType)

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

我多年没有使用Java了,而且我正在快速恢复它,但是Java确实可以轻松地做到这一点,而无需深入研究Reflection API?

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

有帮助吗?

解决方案

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

更多信息此处

其他提示

您只能将 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

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

请参阅 Sun的教程

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top