java.util
类 Properties
java.lang.Objectjava.util.Dictionary<K,V>
java.util.Hashtable<Object,Object>
java.util.Properties
-
所有已实现的接口:
- Serializable, Cloneable, Map< Object, Object>
-
直接已知子类:
- Provider
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
一个属性列表可包含另一个属性列表作为它的“默认值”;如果未能在原有的属性列表中搜索到属性键,则搜索第二个属性列表。
因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用put 和putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是String 的项。相反,应该使用setProperty 方法。如果在“不安全”的Properties 对象(即包含非String 的键或值)上调用store 或 save 方法,则该调用将失败。类似地,如果在“不安全”的Properties 对象(即包含非String 的键)上调用propertyNames 或list 方法,则该调用将失败。
setProperty
public Object setProperty(String key, String value)
-
调用
Hashtable 的方法
put。使用 getProperty 方法提供并行性。强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用put的结果。 -
-
参数:
-
key- 要置于属性列表中的键。 -
value- 对应于 key 的值。
返回:
-
属性列表中指定键的旧值,如果没有值,则为
null。
-
load与setProperty最终通过Hashtable中put方法实现:
/**
* Maps the specified <code>key</code> to the specified <code>value</code> in this hashtable. Neither the key nor the value
* can be <code>null</code>.
* <p>
*
* The value can be retrieved by calling the <code>get</code> method with a key that is equal to the original key.
*
* @param key
* the hashtable key
* @param value
* the value
* @return the previous value of the specified key in this hashtable, or <code>null</code> if it did not have one
* @exception NullPointerException
* if the key or value is <code>null</code>
* @see Object#equals(Object)
* @see #get(Object)
*/
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K, V> e = tab[index]; e != null; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
}
modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K, V> e = tab[index];
tab[index] = new Entry<K, V>(hash, key, value, e);//引用传递,改变了table的值
count++;
return null;
}
Java Properties 类详解
本文深入解析 Java 中的 Properties 类,包括其用途、属性、方法以及如何安全地使用它来存储和检索属性集。

706

被折叠的 条评论
为什么被折叠?



