instanceof
是 Java 中的一个双目运算符,用于测试一个对象是否为某个类的实例。其用法是通过表达式 boolean result = obj instanceof Class
来实现,其中 obj
代表一个对象,而 Class
表示一个类或接口。如果 obj
是 Class
的对象,或者是其直接或间接的子类,或者实现了该接口,结果将返回 true
;否则返回 false
。
需要注意的是,编译器会检查 obj
是否可以转换为右侧的类类型。如果不能进行转换,编译器会直接报错。而在某些情况下,如果类型无法确定,编译时会通过,但实际的结果会在运行时确定。例如,在以下代码中:
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
// 在 Java SE 规范中,如果 obj 为 null,结果将返回 false。
System.out.println(null instanceof Object); // false
可以看到,基本类型的变量 i
无法通过 instanceof
进行测试,因为它必须是引用类型。此外,根据 Java SE 规范,当 obj
为 null
时,instanceof
的结果也将返回 false
。