JAVA instanceof运算符

概述

instanceof 用来测试一个对象是否为一个类的实例

用法

boolean result = obj instanceof Class
  • obj 为一个对象
  • Class 表示一个类或者一个接口

当 obj 为 Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result 都返回 true,否则返回false。

编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。

用法

obj 必须为引用类型,不能是基本类型

int i = 0;
System.out.println(i instanceof Integer);//编译不通过
System.out.println(i instanceof Object);//编译不通过

instanceof 运算符只能用作对象的判断。

obj 为 null

System.out.println(null instanceof Object);//false

在 JavaSE规范 中对 instanceof 运算符的规定就是:如果 obj 为 null,那么将返回 false。

obj 为接口的实现类

了解Java 集合的,我们知道集合中有个上层接口 List,其有个典型实现类 ArrayList

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

所以我们可以用 instanceof 运算符判断 某个对象是否是 List 接口的实现类,如果是返回 true,否则返回 false

ArrayList arrayList = new ArrayList();
System.out.println(arrayList instanceof List);//true

或者反过来也是返回 true

List list = new ArrayList();
System.out.println(list instanceof ArrayList);//true

obj 与 无关接口

interface PersonInter{

}
Person p1 = new Person();

System.out.println(p1 instanceof PersonInter);//false
System.out.println(p1 instanceof List<?>);//false
System.out.println(p1 instanceof List<Person>);//编译报错

obj 为直接或间接子类

新建一个父类 Person,然后在创建它的一个子类 Man

public class Person {

}

public class Man extends Person{

}

测试:

Person p1 = new Person();
Person p2 = new Man();
Man m1 = new Man();

System.out.println(p1 instanceof Person); // true,p1是Person类型,所以返回true
System.out.println(p2 instanceof Person); // true,p2是Main类型,是Person的子类,所以返回true
System.out.println(m1 instanceof Person); // true,m1是Main类型,是Person的子类,所以返回true


System.out.println(p1 instanceof Man);//false,p1是Person类型,`Person` 不是 `Man` 的子类,所以返回结果为 false
System.out.println(p2 instanceof Man);//true,p2是Main类型,所以返回true
System.out.println(m1 instanceof Man);//true,m1是Main类型,所以返回true

obj 与 class 不是父子类

此时编译报错

Person p1 = new Person();

System.out.println(p1 instanceof String);//编译报错

原文出处:/show_1EF4rtJixgXS.html