常见 Java 问题与排错思路
理解常见问题和排错方法是解决实际开发问题的关键。本章将介绍常见 Java 问题与排错思路。
NullPointerException / ClassCastException
NullPointerException
空指针异常是最常见的异常。
// 问题代码
String str = null;
int length = str.length(); // NullPointerException
// 解决方法
// 1. 检查 null
if (str != null) {
int length = str.length();
}
// 2. 使用 Optional
Optional<String> optional = Optional.ofNullable(str);
optional.ifPresent(s -> System.out.println(s.length()));
// 3. 使用 Objects.requireNonNull
String str2 = Objects.requireNonNull(str, "字符串不能为null");
ClassCastException
类型转换异常。
// 问题代码
Object obj = "Hello";
Integer num = (Integer) obj; // ClassCastException
// 解决方法
// 1. 使用 instanceof 检查
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}
// 2. 使用泛型
List<String> list = new ArrayList<>();
// 编译时类型安全