在java中使用“Instance of”[复制]

问题描述 投票:285回答:4

What is the 'instanceof' operator used for?

我了解到Java有instanceof运算符。你能详细说明它的使用地点和优势吗?

java operators instanceof
4个回答
367
投票

基本上,您检查对象是否是特定类的实例。当你有一个超类或接口类型的对象的引用或参数并且需要知道实际对象是否具有其他类型(通常更具体)时,通常使用它。

例:

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"); 
  }
}

请注意,如果您经常使用该运算符,通常会暗示您的设计存在一些缺陷。因此,在设计良好的应用程序中,您应该尽可能少地使用该运算符(当然,该一般规则也有例外)。


67
投票

instanceof用于检查对象是否是类的实例,子类的实例,或实现特定接口的类的实例。

Read more from the Oracle language definition here.


47
投票

instanceof可用于确定对象的实际类型:

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}

26
投票

instanceof是一个关键字,可用于测试对象是否为指定类型。

示例:

public class MainClass {
    public static void main(String[] a) {

    String s = "Hello";
    int i = 0;
    String g;
    if (s instanceof java.lang.String) {
       // This is going to be printed
       System.out.println("s is a String");
    }
    if (i instanceof Integer) {
       // This is going to be printed as autoboxing will happen (int -> Integer)
       System.out.println("i is an Integer");
    }
    if (g instanceof java.lang.String) {
       // This case is not going to happen because g is not initialized and
       // therefore is null and instanceof returns false for null. 
       System.out.println("g is a String");
    } 
} 

这是我的source

© www.soinside.com 2019 - 2024. All rights reserved.