“instanceof”运算符的用途是什么? https://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for
我了解到 Java 有instanceof
操作员。您能否详细说明一下它的用途以及它的优点是什么?
基本上,您检查一个对象是否是特定类的实例。
当您拥有对超类或接口类型的对象的引用或参数并且需要知道实际对象是否具有其他类型(通常更具体)时,通常会使用它。
Example:
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");
}
}
请注意,如果您必须经常使用该运算符,通常表明您的设计存在一些缺陷。因此,在设计良好的应用程序中,您应该尽可能少地使用该运算符(当然,该一般规则也有例外)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)