instanceof严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例,用法为:
boolean result = obj instanceof Class
其中obj为一个对象,Classb表示一个类或者接口,当obj为Class的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result都返回true,否则返回false.
注意:
编译器会检查obj是否能否转换成右边的class类型,如果不能转换直接报错,如果不能确定,则通过编译,具体看运行时定。
int i = 0;
// 编译不通过,i必须是引用类型,不能实是基本类型
System.out.println(i instanceof Integer);
// 编译不通过
System.out.println(i instanceof Object)
Integer integer = new Integer(1);
// true
System.out.ptinln(integer instanceof Integer);
// false,在Java SE 规范中对instanceof运算符的规定就是:如果obj为null,那么将返回false
System.out.println(null instanceof Object);