1. instanceof 是什么?
instanceof 是 Java 中的一个 运算符。
用于检查某个对象是否属于某个类(或其子类、接口实现类)的实例。
返回值:它返回一个 boolean 值
- true-:对象是指定类型(或其子类/实现类)。
- false-:对象不是指定类型,或者是 null。
2. 基本语法
语法:对象+ instanceof +类型
示例:
Object obj = "Hello";
boolean isString = obj instanceof String;
// true,因为 obj 是 String 类型
3. 主要用途
(1) 类型检查(避ClassCastException))
-- ClassCastException 是 Java 中的一个 运行时异常(Runtime Exception),表示 “类型转换失败”。当试图将一个对象强制转换为它 “实际类型不匹配的类” 时,JVM 就会抛出这个异常。
在强制类型转换前,先用 instanceof 检查:
Object obj= 123; //obj 实际是 Integr(整型)
if (obj instanceof String) {
String str = (String) obj;
// 不会执行,因为 obj 不是 String
} else {
System.out.println("obj 不是 String 类型!");
}
(2) 多态场景下的类型判断
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
Animal animal = new Dog();
if (animal instanceof Dog) {
System.out.println("这是一只狗");
} else if (animal instanceof Cat) {
System.out.println("这是一只猫");
}
(3) 检查接口实现
List<String> list = new ArrayList<>();
boolean isList = list instanceof List;
// true(ArrayList 实现了 List)
boolean isSerializable = list instanceof Serializable;
// true(ArrayList 可序列化)
4. 特殊情况
(1) null 的判断
null 用 instanceof 检查任何类型都会返回false:
Object obj = null;
boolean isString = obj instanceof String; // false
(2) 继承与接口的兼容性
instanceof 不仅检查直接类型,还检查继承链和接口实现:
class Parent {}
class Child extends Parent {}
Child child = new Child();
boolean isParent =child instanceof Parent;
// true(Child 是 Parent 的子类)
5. 实际应用场景
(1) 避免类型转换错误
public void process(Object obj) {
if (obj instanceof String) {
String str = (String) obj; //强转
System.out.println(str.toUpperCase());
} else {
System.out.println("不是字符串类型!");
}
}
(2) 处理多种子类逻辑
public void feed(Animal animal) {
if (animal instanceof Dog) {
((Dog) animal).bark();
} else if (animal instanceof Cat) {
((Cat) animal).meow();
}
}
(3) 实现安全的 equals() 方法
@Override //重写父类 equals 方法
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
return this.name.equals(other.name);
}
这段代码实现了 Person 类中 equals 方法的自定义逻辑,用于比较两个 Person 对象是否相等,主要依据是它们的 name 属性。
6. 总结
- instanceof 用于运行时类型检查,避免 ClassCastException。
- 支持继承和接口:子类对象+ instanceof +父类 → true。
- null instanceof AnyType 永远返回 false。