instanceof严格来说是Java中的一个双目运算符,用来判断一个对象是否为一个类的实例

用法:boolean result = obj instance of 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为class类的实例对象

Integer integer = new Integer(1);
System.out.println(integer instanceof Integer); //true

obj为class接口的实现类

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

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

obj为class类的直接或间接子类

新建一个父类Person.class,然后创建一个子类Man.class

public class Person{

}

Man.class

public class Man extends Person{

}

测试:

Person p1 = new Person();
Person p2 = new Man();
Man m1 = new Man();
System.out.println(p1 instanceof Man); //false
System.out.println(p2 instanceof Man); //true
System.out.println(m1 instanceof Man); //true

在第一种情况中,因为Man是Person的子类,但是Person不是Man的子类,因此p1 instanceof Man会返回false

原理

使用伪代码描述:

// obj instanceof T
boolean result;
if (obj == null) {
result = false;
} else {
try {
T temp = (T) obj; // checkcast
result = true;
} catch (ClassCastException e) {
result = false;
}
}

用中文说就是:如果有表达式 obj instanceof T,那么如果obj不为null并且(T)obj不抛ClassCastException异常则该表达式值为true,否则值为false。