gpt4 book ai didi

java - Java 泛型中没有抛出 ClassCastException

转载 作者:太空狗 更新时间:2023-10-29 23:03:51 25 4
gpt4 key购买 nike

下面是我写过的第一个 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()");
}
}

}

结果是“exception outside castToAnotherType()”。为什么泛型方法内部没有发生异常?

最佳答案

T 在编译期间被有效地删除。参见 here :

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety. Generate bridge methods to preserve polymorphism in extended generic types.
  • Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

因此您的castToAnotherTypeT 删除为ca。以下内容:

public static Object castToAnotherType(Object param) {
Object ret = null;
try {
ret = (Object) param;
} catch (ClassCastException e) {
System.out.print("Exception inside castToAnotherType()");
}
return ret;
}

这显然不会产生任何 ClassCastException

main(...) 是一个不同的故事,它的结果如下:

public static void main(String[] args) {
try {
String obj = (String) MyClass.castToAnotherType(new Object());
} catch (ClassCastException e) {
System.out.print("Exception outside castToAnotherType()");
}
}

在尝试将 Object 转换为 String 时会产生 ClassCastException

请参阅Type Erasure的一部分 Generics tutorial .

关于java - Java 泛型中没有抛出 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com