instanceof 是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例,用法为:
boolean result = obj instanceof Class
其中 obj 为一个对象,Class 表示一个类或者一个接口,当 obj 为 Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result 都返回 true,否则返回false。
注意:编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。
1、obj 必须为引用类型,不能是基本类型
int i = 0;
System.out.println(i instanceof Integer);//编译不通过
System.out.println(i instanceof Object);//编译不通过
2、obj 为 null
System.out.println(null instanceof Object);//false
关于 null 类型的描述:https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1null
null本身不是对象,也不是Objcet的实例。
在 JavaSE规范 中对 instanceof 运算符的规定就是:如果 obj 为 null,那么将返回 false。
3、obj 为 class 类的实例对象,或者是其直接或间接子类,或者是其接口的实现类
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList arrayList = new ArrayList();
List list1 = new ArrayList();
List list2 = new List();
System.out.println(arrayList instanceof ArrayList);//true
System.out.println(arrayList instanceof List);//true
System.out.println(List1 instanceof ArrayList);//true
System.out.println(List1 instanceof List);//true
System.out.println(List2 instanceof ArrayList);//false
System.out.println(List2 instanceof List);//true
建一个父类 Person.class,和它的一个子类 Student.class
public class Person {}
public class Person{} extends Person{}
测试:
Person p1 = new Person();
Person p2 = new Student();
Student s1 = new Student();
System.out.println(p1 instanceof Student);//false
System.out.println(p2 instanceof Student);//true
System.out.println(s1 instanceof Student);//true
System.out.println(p1 instanceof Person);//true
System.out.println(p2 instanceof Person);//true
System.out.println(s1 instanceof Person);//true