instanceof 操作符
概述
instanceof 用于检查对象是否是某个类的实例。
基本概念
用法
java
if (obj instanceof Type) {
// obj 是 Type 类型
}代码示例
基本使用
java
public class InstanceofBasicDemo {
static class Animal {}
static class Dog extends Animal {}
static class Cat extends Animal {}
public static void main(String[] args) {
Animal animal = new Dog();
// instanceof 检查
System.out.println(animal instanceof Animal); // true
System.out.println(animal instanceof Dog); // true
System.out.println(animal instanceof Cat); // false
}
}Pattern Matching (JDK 16+)
java
public class InstanceofPatternDemo {
static class Animal {}
static class Dog extends Animal {
void bark() {
System.out.println("Woof!");
}
}
public static void main(String[] args) {
Object obj = new Dog();
// 传统方式
if (obj instanceof Dog) {
Dog dog = (Dog) obj;
dog.bark();
}
// Pattern Matching (JDK 16+)
if (obj instanceof Dog dog) {
dog.bark();
}
}
}继承检查
java
public class InstanceofInheritDemo {
static class Fruit {}
static class Apple extends Fruit {}
static class RedApple extends Apple {}
public static void main(String[] args) {
Fruit fruit = new RedApple();
// 继承链检查
System.out.println(fruit instanceof Fruit); // true
System.out.println(fruit instanceof Apple); // true
System.out.println(fruit instanceof RedApple); // true
}
}注意事项
- 检查继承:子类对象也是父类实例
- Pattern Matching:JDK 16+ 简化语法
- 避免 ClassCastException:先检查再转换
