为什么 Java 不允许 Throwable 的泛型子类? [英] Why doesn't Java allow generic subclasses of Throwable?
问题描述
根据 Java 语言规范,第 3 版:
这是一个编译时错误,如果一个泛型class 是 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?
(据我所知,泛型只是编译时的语法糖,它们无论如何都会在 .class
文件中被转换为 Object
,因此有效地声明泛型类就好像其中的所有内容都是 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
和 SomeException
都被擦除为同一类型,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屋!