java - 即使不使用 put(),对象的属性也会在 Map 中更改吗?

标签 java dependency-injection inversion-of-control

嗨,我从一本书上得到了代码:

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"

这里都是firstsecond是对相同StringBuilder的引用对象...当您通过 first.append() 更改该对象的内容时,当您通过second查看对象时,该变化仍然可见。在后续行中引用。

关于java - 即使不使用 put(),对象的属性也会在 Map 中更改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1137615/

相关文章:

java - Java 中用于串行调用方法的正确约定

java - LIBGDX 在一个屏幕上制作 5 个不同的按钮

java - 在 Java 编程中使用模块

php - Symfony DI : Circular service reference with Doctrine event subscriber

C#工厂模式和IoC的区别

java - 我是否需要关闭 PipedInputStream 和 PipedOutputStream

dependency-injection - 使用 Autofac 的 OWIN 服务解析

c# - ASP.NET MVC3 + ActionFilterAttribute + 注入(inject)?

dependency-injection - 带有 funq 的 servicestack - 按照惯例 Autowiring

mvvm - 为什么在 ViewModelLocator 中将 MEF 用于设计时/运行时?