数组协变带来的静态类型漏洞 - 编程入门网
lot of very, very hard constraints. The strongest constraint, the most difficult to cope with, was that it had to be fully backwards compatible with ungenerified Java. The story was the collections library had just shipped with 1.2, and Sun was not prepared to ship a completely new collections library just because generics came about. So instead it had to just work completely transparently.
That''s why there were a number of fairly ugly things. You always had to have ungenerified types with generified types, the so called raw types. Also you couldn''t change what arrays were doing so you had unchecked warnings. Most importantly you couldn''t do a lot of the things you wanted to do with arrays, like generate an array with a type parameter T, an array of something where you didn''t know the type. You couldn''t do that. Later in Scala we actually found out how to do that, but that was possible only because we could drop in Scala the requirement that arrays are covariant. Bill Venners: Can you elaborate on the problem with Java''s covariant arrays? Martin Odersky: When Java first shipped, Bill Joy and James Gosling and the other members of the Java team thought that Java should have generics, only they didn''t have the time to do a good job designing it in. So because there would be no generics in Java, at least initially, they felt that arrays had to be covariant. That means an array of String is a subtype of array of Object, for example. The reason for that was they wanted to be able to write, say, a “generic” sort method that took an array of Object and a comparator and that would sort this array of Object. And then let you pass an array of String to it. It turns out that this thing is type unsound in general. That''s why you can get an array store exception in Java. And it actually also turns out that this very same thing blocks a decent implementation of generics for arrays. That''s why arrays in Java generics don''t work at all. You can''t have an array of list of string, it''s impossible. You''re forced to do the ugly raw type, just an array of list, forever. So it was sort of like an original sin. They did something very quickly and thought it was a quick hack. But it actually ruined every design decision later on. So in order not to fall into the same trap again, we had to break off and say, now we will not be upwards compatible with Java, there are some things we want to do differently. P.S. 不知道协变是什么的同学可以读读Wikipedia上的词条 P.P.S 不认识Martin Odersky的同学请留意:只要用到Java 5的泛型,你们的代码里就有他的痕迹。 他是Pizza语言的设计者,后来参与了GJ(Generic Java)的设计;后者就是后来Java 5中的泛型的基石 。Martin还设计了Scala << 知道Scala的人肯定比知道Pizza的多多了…… |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |