意外类型安全违规 [英] Unexpected type safety violation

查看:98
本文介绍了意外类型安全违规的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,显式不兼容类型的dowcast传递编译:

In the following code, a dowcast to an apparently incompatible type passes compilation:

public class Item {
  List<Item> items() { return asList(new Item()); }
  Item m = (Item) items();
}

code> List< Item> 是不同的类型,所以强制转换永远不会成功。为什么编译器允许这样?

Item and List<Item> are disparate types so the cast can never succeed. Why did the compiler allow this?

推荐答案

A List< Item> 可以很好地是一个项目。例如:

A List<Item> could very well be an Item. See for example:

public class Foo extends Item implements List<Item> {
    // implement required methods
}

我知道你不能确定这是一个类型的对象,但我知道比你更好,所以请编译。编译器只会拒绝编译,如果返回的对象不可能是Item的实例(例如, Integer 不能是一个 String

A cast tells the compiler: "I know you can't be sure that this is a object of type Item, but I know better than you, so please compile". The compiler will only refuse to compile that if it's impossible for the returned object to be an instance of Item (like, for example, Integer can't ever be a String)

在运行时,将检查方法返回的实际对象的类型,对象类型为Item,你会得到一个ClassCastException。

At runtime, the type of the actual object returned by the method will be checked, and if it's not actually an object of type Item, you'll get a ClassCastException.

这篇关于意外类型安全违规的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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