使用“instanceof"在 Java 中 [英] Use of "instanceof" in Java

查看:25
本文介绍了使用“instanceof"在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'instanceof' 运算符的用途是什么?

我了解到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆