java.util.Properties类用于表示键和值都是字符串的映射.这是因为Properties对象用于读取.properties文件,这些文件是文本文件.
那么,为什么在Java 5中他们改进了这个类来实现Map< Object,Object>而不是Map< String,String>?
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a “compromised” Properties object that contains a non-String key or value, the call will fail.
由于键和值都应该是字符串,那么为什么不使用正确的泛型类型静态强制执行呢?
我想使Properties实现Map< String,String>将不会完全向后兼容为Java 5之前编写的代码.如果您有旧的代码将非字符串粘贴到Properties对象中,那么该代码将不再使用Java 5编译.但是……这不是一个好的事情?在编译时捕获这种类型错误不是泛型的全部意义吗?