简体   繁体   English

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

[英]What is the easiest way to do 'is' in Java?

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. 我在这里和其他地方搜索过,但所涉及的关键词非常通用,即使我确定这有一个简单的答案,谷歌搜索它很难。

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

More info here . 更多信息在这里

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

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的教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM