Java泛型中不会抛出ClassCastException [英] No ClassCastException is thrown inside Java generics

查看:144
本文介绍了Java泛型中不会抛出ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我写过的第一个Java泛型:

Below is the first Java generics I've ever written :

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()");
        }
    }

}

结果是castToAnotherType()之外的异常。为什么在泛型方法中不会发生异常?

The result is "Exception outside castToAnotherType()". Why did the exception not occur inside the generic method?

推荐答案

T 在编译期间被有效擦除。请参阅此处

T is effectively erased during compilation. See here:


泛型被引入到Java语言中,以便在编译时提供更严格的类型
检查并支持泛型编程。为了
实现泛型,Java编译器将类型擦除应用于:

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:


  • 用泛型或$替换泛型类型中的所有类型参数b $ b对象,如果类型参数是无界的。因此,生成的字节码
    仅包含普通的类,接口和方法。

  • 如有必要,插入类型转换以保持类型安全。生成
    桥接方法以保留扩展泛型类型中的多态性。

  • 类型擦除确保不为参数化
    类型创建新类;因此,泛型不会产生运行时开销。

所以你的 castToAnotherType 获取 T 删除到ca.以下内容:

So your castToAnotherType gets T erased into ca. the following:

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(...)是一个不同的故事,结果如下:

main(...) is a different story, it results into the following:

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

产生 ClassCastException 尝试将 Object 强制转换为 String

Which produces the ClassCastException when trying to cast Object to String.

请参阅 Type Erasure 部分http://docs.oracle.com/javase/tutorial/java/generics/index.html\">泛型教程。

Please see the Type Erasure part of the Generics tutorial.

这篇关于Java泛型中不会抛出ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆