直接通用例外 [英] Direct Generic Exceptions
问题描述
我的问题是这个问题的后续行动:
My question is a follow-up to this question:
问题得到了完美的回答,但是只有在间接通用异常中,那就是:
The question was answered perfectly, but only on indirect generic exception, that's:
public class MyException<T> extends Exception {
留下的是void,是直接泛型: p>
What was left void, is direct generics:
public static <T extends Exception> void checkForException(Class<T> exType) {
try {
// some code
} catch (T e) {
e.printStackTrace();
}
}
为什么不允许?
尽管我认为这是不允许的唯一原因是, T
可能是一种类型,也被明确地捕获:
Why is this not allowed?
Though, the only reason I could think this is not allowed, is that T
could be a type, that is also explicitly caught:
// if T is IOException
catch(T e) { }
catch(IOException e) { }
但这是阻止它的好理由吗?
同样的效果,也可以在没有泛型的情况下完成:
But is this a good reason to block it? The same effect, could as well be done without generics too:
catch(Exception e) { }
catch(IOException e { }
这是文档上述限制。
推荐答案
因为在Java类型变量中,即 T 是不可重新由于 类型擦除 。
Because in Java Type Variables, i.e. T, are not reifiable due to Type Erasure.
这意味着编译器没有 T 。
所以没有办法阻止你的人会知道什么 T 原来是,而不是,你不能把它当作基本类型。那会做一些完全不同的事情。如果你有
Hence there is no way that catch block of yours will ever know what T originally was. And no, you can't just treat it as the base type. That would do something completely different. What if you had
catch(T e) { }
catch(MyBaseException e) { }
catch(MyApplicationException e) { }
和 T 扩展MyBaseException 。看看这真的很难真的很快?
and T extends MyBaseException. See how that got really bad really quick?
阅读更多在优秀的 Java泛型常见问题 - 在编译器的罩下
我从来没有喜欢类型擦除,而是语言设计师发誓他们有使用它的原因。所以我们在这里。
Personally I've never liked type erasure, but the language designers swore they had their reasons for using it. So here we are.
这篇关于直接通用例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!