Java:为什么在调用 .readObject() 时,具有引用泛型类型的 ArrayList 不计为强制转换?
我正在从保存文件加载 ArrayList
,该文件具有推断的泛型类型,但 eclpise 告诉我我还没有检查强制转换,为什么不 (ArrayList
算作强制转换吗?(TypeOfObject)
算作强制转换时,
game.evilSprites = (ArrayList<EvilSprite>) OIS.readObject();
将对象转换为邪恶精灵有效...
game.evilSprite = (EvilSprite) OIS.readObject();
编辑:太好了,谢谢,所以它至少是一个有效的转换,我如何检查它以删除警告?
I am loading an ArrayList
from a save file which has a generic type inferred, but eclpise is telling me I haven't checked the cast, why doesn't (ArrayList< TypeOfObject >)
count as a cast when (TypeOfObject)
does?
game.evilSprites = (ArrayList<EvilSprite>) OIS.readObject();
casting the object as an evilSprite works...
game.evilSprite = (EvilSprite) OIS.readObject();
EDIT: great, thank you, so it is at least a valid cast, how do I check it to remove the warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它确实算作强制转换,但无法正确检查。在执行时,由于类型擦除,对象没有关于它是否是
ArrayList
、ArrayList
It does count as a cast, but it can't be checked properly. At execution time, an object has no information about whether it's an
ArrayList<String>
, anArrayList<Object>
etc, due to type erasure. So your cast is checking that it's anArrayList
of some kind, but you could still get aClassCastException
when you try to fetch a sprite out of it - the values may not all beEvilSprite
references.