使用"instanceof"实例.在Java中 [英] Use of "instanceof" in Java
问题描述
我了解到Java具有instanceof
运算符.您能详细说明它的使用位置及其优点吗?
I learned that Java has the instanceof
operator. Can you elaborate where it is used and what are its advantages?
推荐答案
基本上,您检查对象是否为特定类的实例. 当您对超类或接口类型的对象具有引用或参数,并且需要知道实际对象是否具有其他类型(通常更具体)时,通常可以使用它.
Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).
示例:
public void doSomething(Number param) {
if( param instanceof Double) {
System.out.println("param is a Double");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}
if( param instanceof Comparable) {
//subclasses of Number like Double etc. implement Comparable
//other subclasses might not -> you could pass Number instances that don't implement that interface
System.out.println("param is comparable");
}
}
请注意,如果您必须经常使用该运算符,通常表明您的设计存在缺陷.因此,在设计良好的应用程序中,您应该尽可能少地使用该运算符(当然,该通用规则也有例外).
Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).
这篇关于使用"instanceof"实例.在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!