Java:将 MyClass 转换为列表<MyClass>
Java: Casting MyClass to List<MyClass>
为什么可以将 MyClass
对象转换为 List<MyClass>
而不会出现编译错误(只有 'unchecked' 警告),尽管 MyClass
没有实现 List 接口,并且同时不可能以相同的方式投射,例如 String
class。
谢谢。
如果转换完全不可能,编译器将创建一个编译器错误。但是当你转换到一个界面时(你原来的 class 不是 final
),这个转换是有可能成功的。
有可能,即使它可能不存在,对于您尚未编写的 class class MyClass
和实现 List
,甚至如果这对我们没有意义。
由于这种可能性,编译器必须允许这种转换。但是如果没有这样的 subclass,这仍然会在运行时导致 ClassCastException
。
JLS, Section 5.5.1,将 S
转换为 T
时的状态:
If T is an interface type:
If S is not a final class (§8.1.1), then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.
Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).
If S is a final class (§8.1.1), then S must implement T, or a compile-time error occurs.
(大胆强调我的)
为什么可以将 MyClass
对象转换为 List<MyClass>
而不会出现编译错误(只有 'unchecked' 警告),尽管 MyClass
没有实现 List 接口,并且同时不可能以相同的方式投射,例如 String
class。
谢谢。
如果转换完全不可能,编译器将创建一个编译器错误。但是当你转换到一个界面时(你原来的 class 不是 final
),这个转换是有可能成功的。
有可能,即使它可能不存在,对于您尚未编写的 class class MyClass
和实现 List
,甚至如果这对我们没有意义。
由于这种可能性,编译器必须允许这种转换。但是如果没有这样的 subclass,这仍然会在运行时导致 ClassCastException
。
JLS, Section 5.5.1,将 S
转换为 T
时的状态:
If T is an interface type:
If S is not a final class (§8.1.1), then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.
Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).
If S is a final class (§8.1.1), then S must implement T, or a compile-time error occurs.
(大胆强调我的)