Java 中的泛型是否避免所有 ClassCastExceptins?
由于 Java 5 仅在编译时检查泛型,因此它们能否在所有情况下避免 ClassCastExceptions 情况?
Since generics are only checked during compile time with Java 5, can they avoid ClassCastExceptions in all
situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 5 泛型提供的“铁证”保证是,只要编译器没有产生“未经检查”的警告,您就永远不会在编译器插入的强制转换中看到 ClassCastException。
在现实生活中,如果您的代码使用遗留(非通用)库,您通常无法避免未经检查的警告。 然后,编译器生成的强制转换可能抛出ClassCastException,您的工作就是通过确保库代码返回的值对于您的声明而言类型正确来防止这种情况发生。
否则情况不变。 在泛型之外,如果您转换为不兼容的类型,您将像往常一样得到 ClassCastException。
(对于这个问题和其他泛型问题,Java 泛型和集合是一个很好的参考。)
The "cast-iron" guarantee that Java 5 generics provides is that you will never see a ClassCastException from the casts inserted by the compiler provided that compilation produced no "unchecked" warnings.
In real life, you often can't avoid unchecked warnings if your code uses legacy (non-generified) libraries. Then the compiler-generated casts can throw ClassCastException, and it's your job to prevent this by ensuring that the values returned by library code are well-typed for your declarations.
Otherwise the situation is unchanged. Outside of generics, if you cast to an incompatible type you'll get a ClassCastException the same way as you always did.
(A good reference for this and other generics questions is Java Generics and Collections.)
首先,您应该确保您的代码在编译时不会出现未检查的警告。 这是一个很好的指标。 要了解原因,我建议您查看 Effective Java 中的泛型示例章节。
其次,泛型无法保护您免受以下代码的影响:
第三,如果您以某种方式弄乱了类加载器,您可能会遇到奇怪的
ClassCastExceptions
,例如 < a href="http://www.techienuggets.com/Comments?tx=5498" rel="nofollow noreferrer">此讨论主题。 让人看得心都麻木所以答案是不,仅仅通过正确使用泛型是无法摆脱
ClassCastException
的。。First of all, you should make sure that your code compiles without unckeched warnings. That is a good indicator. To understand why, I suggest you take a look at the sample chapter for generics from Effective Java.
Second of all, generics can't guard you from code such as:
Third of all, if you're in some way or another messing with Class Loaders, you might get strange
ClassCastExceptions
, such as in this discussion thread. It is mind-numbing to seeSo the answer is no, you can't get rid of
ClassCastException
s just by properly using generics.不。使用 Java 5.0 和泛型类型并不能让您免受 ClassCastException 的影响。
No. Using Java 5.0 and generics type doesn't make you ClassCastException-proof.
没有。 泛型只能避免编译时错误,不能避免运行时异常。
Nope. generics only save you from compile time errors, not runtime exceptions.