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