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

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

问题描述

我想我得到了不加控制的投射手段(从一个到另一个类型的投射),但是检查这个角色是什么意思?如何检查演员表,以便我可以在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?

推荐答案

未选中的转换表示您(隐式或显式地)从通用类型转换为非限定类型或其他方式。例如。这行

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(未选中)注释。如果禁止警告
,而不首先证明代码是类型安全的,那么您只会给自己一个
的虚假安全感。代码可以编译而不发出任何警告,但
它仍然可以在运行时抛出一个 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天全站免登陆