没有 ClassCastException 被抛入 Java 泛型中
2022-09-04 00:54:54
以下是我写过的第一个Java泛型:
public class MyClass {
public static <T> T castToAnotherType(Object param) {
T ret = null;
try {
ret = (T) param;
} catch (ClassCastException e) {
System.out.print("Exception inside castToAnotherType()");
}
return ret;
}
public static void main(String[] args) {
try {
String obj = MyClass.castToAnotherType(new Object());
} catch (ClassCastException e) {
System.out.print("Exception outside castToAnotherType()");
}
}
}
结果是“CastToOtherType()之外的异常”。为什么泛型方法中没有发生异常?