java - Java 泛型中没有抛出 ClassCastException

标签 java generics classcastexception

下面是我写过的第一个 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/

相关文章:

BufferedImage 的 Java 抗锯齿

java - Kotlin上的Server-Client应用程序出现问题

java - 让我的scrollPane在程序控制下滚动

java - 使用泛型的 Hashmap getter setter

spring-mvc - Spring MVC——java.lang.ClassCastException

java - EJB 3 RemoteInterface 类在查找期间强制转换异常

java - 如何在Java中通过格式化来居中字符串?

c# - XAML 中的通用 IValueConverter C# WPF 用法?

swift - 泛型执行请求,使用泛型

迭代 For 循环时,java.lang.String 无法转换为 [Ljava.lang.Object