为什么Java不允许Throwable的通用子类? [英] Why doesn't Java allow generic subclasses of Throwable?

查看:189
本文介绍了为什么Java不允许Throwable的通用子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Java语言识别,第3版:


如果通用类是 Throwable 的直接或间接子类,则是编译时错误。

It is a compile-time error if a generic class is a direct or indirect subclass of Throwable.

我想了解为什么这个决定已经完成。通用异常有什么问题?

I wish to understand why this decision has been made. What's wrong with generic exceptions?

(据我所知,泛型是简单的编译时语法糖,它们将被翻译成 Object 无论如何,在 .class 文件中,所以有效地声明一个通用类就好像它的一切都是一个 Object 如果我错了,请更正我。)

(As far as I know, generics are simply compile-time syntactic sugar, and they will be translated to Object anyway in the .class files, so effectively declaring a generic class is as if everything in it was an Object. Please correct me if I'm wrong.)

推荐答案

正如Mark所说,这些类型不可以,这是以下情况的问题:

As mark said, the types are not reifiable, which is a problem in the following case:

try {
   doSomeStuff();
} catch (SomeException<Integer> e) {
   // ignore that
} catch (SomeException<String> e) {
   crashAndBurn()
}

SomeException< Integer> SomeException< String> 被删除为相同类型,JVM无法区分异常实例,因此无法确定哪个 catch 块应该执行。

Both SomeException<Integer> and SomeException<String> are erased to the same type, there is no way for the JVM to distinguish the exception instances, and therefore no way to tell which catch block should be executed.

这篇关于为什么Java不允许Throwable的通用子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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