嗨,我从一本书上得到了代码:
public class Container {
Map<String, Object> components;
public Container() {
components = new HashMap<String, Object>();
Properties properties = new Properties();
try {
properties.load(new FileInputStream("components.properties"));
for (Map.Entry entry : properties.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
processEntry(key, value);
}
} catch (Exception ex) {
throw new RuntimeException();
}
}
private void processEntry(String key, String value) throws Exception {
String parts[] = key.split("\\.");
if (parts.length == 1) {
Object component = Class.forName(value).newInstance();
components.put(parts[0], component);
} else {
Object component = components.get(parts[0]);
Object reference = components.get(value);
PropertyUtils.setProperty(component, parts[1], reference);
}
}
public Object getComponent(String id) {
return components.get(id);
}
}
我的问题是,上线
PropertyUtils.setProperty(component, parts[1], reference);
Map 中对象的属性已更改。即使更新属性后,没有 component.put() 来更新 map 内的对象,该对象也会更新。这是为什么?
最佳答案
这是因为 map 仅包含对象的引用 - 而不是对象的副本。
当您更改对象中的某些内容时,您可以通过任何方式看到该更改 - 无论是否通过 map 中的引用。
这与做(比如说)完全相同:
StringBuilder first = new StringBuilder();
StringBuilder second = first;
first.append("Hello");
System.out.println(second); // Prints "Hello"
这里都是first
和second
是对相同StringBuilder
的引用对象...当您通过 first.append()
更改该对象的内容时,当您通过second
查看对象时,该变化仍然可见。在后续行中引用。
关于java - 即使不使用 put(),对象的属性也会在 Map 中更改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1137615/