什么是未经检查的投放,我如何检查? [英] What is unchecked cast and how do I check it?

查看:218
本文介绍了什么是未经检查的投放,我如何检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我得到了不受限制的投射意味着(从一个到另一个不同类型的投射),但是检查投射是什么意思?如何检查转换,以便我可以避免在Eclipse中的警告?
感谢,

I think I get what unchecked cast means (casting from one to another of a different type), but what does it mean to "Check" the cast? How can I check the cast so that I can avoid this warning in Eclipse? Thanks,

推荐答案

未经检查的转换意味着你(隐式或显式)从一个泛型类型转换为一个非限定类型或其他方式。例如。此行

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around. E.g. this line

Set<String> set = new HashSet();

会产生此类警告。

通常有这样的警告的一个很好的理由,所以你应该尝试改善你的代码,而不是抑制警告。引用Effective Java,第2版:

Usually there is a good reason for such warnings, so you should try to improve your code instead of suppressing the warning. Quote from Effective Java, 2nd Edition:


取消每个未经检查的警告。如果
消除所有警告,你放心你的代码是类型安全的,这是一个非常
的好东西。这意味着在运行时你不会得到 ClassCastException ,它
增加你的信心,你的程序是按照你的意图。

Eliminate every unchecked warning that you can. If you eliminate all warnings, you are assured that your code is typesafe, which is a very good thing. It means that you won’t get a ClassCastException at runtime, and it increases your confidence that your program is behaving as you intended.

如果你不能消除警告,并且你可以证明
引发的代码是类型安全的,那么(然后)禁止警告
@SuppressWarnings(unchecked)注释。如果你禁止警告
没有先证明代码是类型安全的,你只给自己一个
假的安全感。代码可以编译而不发出任何警告,但
它仍然可以在运行时抛出 ClassCastException 。然而,如果你忽略
未检查的警告,你知道是安全的(而不是抑制他们),你
将不会注意到一个新的警告作物,这代表一个真正的问题。

If you can’t eliminate a warning, and you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with an @SuppressWarnings("unchecked") annotation. If you suppress warnings without first proving that the code is typesafe, you are only giving yourself a false sense of security. The code may compile without emitting any warnings, but it can still throw a ClassCastException at runtime. If, however, you ignore unchecked warnings that you know to be safe (instead of suppressing them), you won’t notice when a new warning crops up that represents a real problem. The new warning will get lost amidst all the false alarms that you didn’t silence.

当然,这是一个错误的警告。并不总是很容易消除警告与上面的代码。没有看到你的代码,没有办法告诉如何使它安全,虽然。

Of course, it is not always as easy to eliminate warnings as with the code above. Without seeing your code, there is no way to tell how to make it safe though.

这篇关于什么是未经检查的投放,我如何检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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