在Java中做“'是'最简单的方法是什么?

时间:2021-06-15 20:02:06

Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:

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

if(obj is MyType)

Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null.

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

I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?

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

Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.

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

3 个解决方案

#1


16  

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

More info here.

更多信息在这里。

#2


7  

You can only use instanceof with a class literal: that is:

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

Class type = String.class;

if (myObj instanceof String) // will compile

if (myObj instanceof type) //will not compile

The alternative is to use the method Class.isInstance

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

if (type.isInstance(myObj)) // will compile

#3


1  

obj instanceof TargetType returns true just in case TargetType is in the type hierarchy that contains obj.

obj instanceof TargetType仅在TargetType位于包含obj的类型层次结构中时返回true。

See Sun's tutorial

请参阅Sun的教程

#1


16  

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

More info here.

更多信息在这里。

#2


7  

You can only use instanceof with a class literal: that is:

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

Class type = String.class;

if (myObj instanceof String) // will compile

if (myObj instanceof type) //will not compile

The alternative is to use the method Class.isInstance

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

if (type.isInstance(myObj)) // will compile

#3


1  

obj instanceof TargetType returns true just in case TargetType is in the type hierarchy that contains obj.

obj instanceof TargetType仅在TargetType位于包含obj的类型层次结构中时返回true。

See Sun's tutorial

请参阅Sun的教程