instanceof 运算符
在类型转换前使用 instanceof 检查对象类型,避免 ClassCastException
instanceof 运算符 是 CoddyKit 上的免费 Java Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。
instanceof 运算符
instanceof 运算符会在运行时检查对象是否为指定类型的实例。它返回 true 或 false,并能在类型转换前避免 ClassCastException。
instanceof 的基本用法
在执行安全的类型转换前,请使用 instanceof 测试对象的运行时类型。
Object obj = "Hello, Java!";
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.toUpperCase()); // HELLO, JAVA!
}
Object num = Integer.valueOf(42);
System.out.println(num instanceof Integer); // true
System.out.println(num instanceof String); // false继承中的 instanceof
如果对象是该类或其任意子类的实例(或者实现了该接口),instanceof 就会返回 true。
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
Animal a = new Dog();
System.out.println(a instanceof Animal); // true
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Cat); // falseinstanceof 的模式匹配(Java 16+)
Java 16 为 instanceof 引入了模式匹配:您可以在同一个表达式中声明绑定变量,从而省略显式类型转换。
Object shape = "circle";
// Old way
if (shape instanceof String) {
String s = (String) shape;
System.out.println(s.length());
}
// New way (Java 16+) — binding variable 's' is in scope
if (shape instanceof String s) {
System.out.println(s.length()); // 6
}方法中的模式匹配
模式匹配让基于类型的分派既清晰又安全。绑定变量只在已知条件为真的作用域内可用。
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
static double area(Shape s) {
if (s instanceof Circle c) {
return Math.PI * c.radius() * c.radius();
} else if (s instanceof Rectangle r) {
return r.width() * r.height();
}
throw new IllegalArgumentException("Unknown shape");
}
System.out.println(area(new Circle(5))); // 78.53...
System.out.println(area(new Rectangle(4, 6))); // 24.0instanceof 与 null
null instanceof AnyType 始终返回 false,不会抛出异常。这使 instanceof 成为一种在类型转换前进行 null 安全检查的方式。
String s = null;
System.out.println(s instanceof String); // false (not NPE)
Object o = null;
if (o instanceof Number n) {
System.out.println(n.intValue());
} else {
System.out.println("Not a number (or null)"); // prints this
}switch 表达式与模式匹配
Java 21 将模式匹配扩展到了 switch 表达式,使您无需使用串联的 if-else,就能清晰地按类型进行路由。
static String describe(Object obj) {
return switch (obj) {
case Integer i -> "Integer: " + i;
case Double d -> "Double: " + d;
case String s -> "String of length " + s.length();
case null -> "null value";
default -> "Unknown: " + obj.getClass().getSimpleName();
};
}
System.out.println(describe(42)); // Integer: 42
System.out.println(describe(3.14)); // Double: 3.14
System.out.println(describe("hello")); // String of length 5
System.out.println(describe(null)); // null value不使用 instanceof 时的 ClassCastException
未先进行检查就执行类型转换,会在运行时导致 ClassCastException。这是旧代码中的常见错误,而模式匹配有助于避免这种问题。
Object obj = "I am a String";
try {
Integer i = (Integer) obj; // ClassCastException!
} catch (ClassCastException e) {
System.out.println("Cannot cast String to Integer");
}
// Safe version
if (obj instanceof Integer i) {
System.out.println("Is integer: " + i);
} else {
System.out.println("Not an integer");
}实践:处理混合列表
一个实际应用场景是:使用模式匹配处理包含不同类型对象的异构列表。
import java.util.List;
List<Object> events = List.of(
"User login", 42, 3.14, "Payment processed", 100
);
double numericSum = 0;
for (Object e : events) {
if (e instanceof Integer n) numericSum += n;
else if (e instanceof Double d) numericSum += d;
else if (e instanceof String s) System.out.println("Log: " + s);
}
System.out.printf("Numeric sum: %.2f%n", numericSum); // 145.14密封类与穷尽匹配
密封类(Java 17+)会限制哪些类可以继承它们。将其与模式匹配 switch 结合使用时,编译器可以验证匹配是否完整,因此不需要 default 分支。
sealed interface Notification permits EmailNotification, SmsNotification {}
record EmailNotification(String to, String body) implements Notification {}
record SmsNotification(String phone, String text) implements Notification {}
static void send(Notification n) {
switch (n) {
case EmailNotification e ->
System.out.println("Email to " + e.to() + ": " + e.body());
case SmsNotification s ->
System.out.println("SMS to " + s.phone() + ": " + s.text());
// no default needed — compiler knows all cases are covered
}
}带保护条件的模式
模式匹配支持使用 when(Java 21)添加保护条件,从而在类型检查的同时加入布尔条件。
static String classify(Number n) {
return switch (n) {
case Integer i when i < 0 -> "negative int: " + i;
case Integer i when i == 0 -> "zero";
case Integer i -> "positive int: " + i;
case Double d -> "double: " + d;
default -> "other number";
};
}
System.out.println(classify(-5)); // negative int: -5
System.out.println(classify(0)); // zero
System.out.println(classify(7)); // positive int: 7快速检查
以下表达式会返回什么?
Object obj = null; boolean result = obj instanceof String; System.out.println(result);
总结:instanceof 运算符
要点:
- instanceof 检查运行时类型,并避免 ClassCastException
- 对 null 返回 false,绝不会抛出 NPE
- 对于类本身及其所有子类或接口实现,都会返回 true
- Java 16+ 的模式匹配:if (x instanceof String s) 将检查与类型转换合并在一起
- Java 21 的带模式 switch 可以按类型清晰地进行路由,并可选择添加保护条件
- 密封类加穷尽 switch 无需 default 分支
常见问题解答
「instanceof 运算符」课时是免费的吗?
是的 — 「instanceof 运算符」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。
「instanceof 运算符」这节课中我会学到什么?
在类型转换前使用 instanceof 检查对象类型,避免 ClassCastException 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Java Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「instanceof 运算符」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Java Academy 课中编写并运行代码吗?
能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 基本类型与引用类型
- 扩大转换与缩小转换
- instanceof 运算符
- 实际应用中的类型转换