字符串被分配给列表而没有编译错误 [英] String gets assigned to a List without a compilation error
问题描述
那么为什么要编译以下代码?
public static void main(String [] args){
String s = getList();
}
private static< T extends List> T getList(){
return(T)new ArrayList();
}
它编译得很好。我的类型安全编译在哪里? getList()
方法与 String
类没有任何共同之处。
String
的子类可能实际上实现了该接口,因此编译器会导致可能存在有效的运行时情况,其中返回的实际对象是 String
,它也是 List
。编译器不认为String是final的,因此实际上不可能创建 List -implementing String
class 。
至于为什么在编译期间不考虑final,Bohemian对这个问题的评论给出了一个很好的解释。
As I know, one of the main purposes of generics in Java is providing compile-time type safety. If it gets compiled, the code will run without issues.
Then why is the following code being compiled?
public static void main(String[] args) {
String s = getList();
}
private static <T extends List> T getList() {
return (T)new ArrayList();
}
It compiles fine. Where is my type-safe compilation? The getList()
method has nothing in common with the String
class.
解决方案 This is not a type erasure problem per se, but almost the opposite: You get a problem at runtime, when the system knows the actual types, but not at compile time. The reason why this compiles is that List
is an interface. As far as the compiler is concerned, a subclass of String
might actually implement that interface, so the compiler reasons that there could be valid runtime situations where the actual object returned is a String
that is also a List
. The compiler does not consider that String is final, and thus that it's impossible to actually create a List
-implementing String
class.
As to why final is not considered during compilation, Bohemian's comment to the question gives a good explanation.
这篇关于字符串被分配给列表而没有编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!