MRa*_*ser 3 java generics casting
为什么以下代码编译?
如果参数是接口而不是泛型的超级接口,为什么允许将通用列表转换为其类型参数?
这是什么意思?
//Connection can be substituted by any interface
List<Connection> list = null;
Connection c = (Connection) list;
Run Code Online (Sandbox Code Playgroud)
Mic*_*rdt 12
这与type参数无关.这也有效:
List<String> list = null;
Connection c = (Connection) list;
Run Code Online (Sandbox Code Playgroud)
这是可能的,因为它List是一种接口类型.这将是可能的列表引用持有的对象,既实现了List接口,并且也是一个Connection(不管它是什么,类或接口),并且其因此剧组工作.
因此,由于演员可以工作,编译器允许它.它只会拒绝理论上不可能的强制转换,即在单独的继承层次结构中涉及具体类型:
JComponent c = null;
ArrayList l = (ArrayList) c;
Run Code Online (Sandbox Code Playgroud)
您可以在Java语言规范中查找编译时哪些类型的强制转换是合法的确切规则- 它是大约30行密集语言律师.