微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用先前在文件

如何解决使用先前在文件

我有一个看起来像这样的 yaml 文件

defaultSettings:
    a: 1
    b: foo
entries:
    - name: one
      settings:
          a: 2
    - name: two
      settings:
          b: bar
    - name: three

假设我有这些类:

class Settings {
    public int a;
    public String b;
}

class Entry {
    public String name;
    public Settings settings;
}

class Config {
    public Settings defaultSettings;
    public List<Entry> entries;
}

关键是我想将文件顶部指定的 defaultSettings 用于单个条目中未指定的任何设置。因此,条目会像这样编写:

    - name: one
      settings:
          a: 2
          b: foo
    - name: two
      settings:
          a: 1
          b: bar
    - name: three
      settings:
          a: 1
          b: foo

有没有好的方法可以做到这一点(例如,使用 Jackson、SnakeYAML 等)?我可以完全控制代码,因此我可以进行修改,如果这会导致更好的做事方式。

解决方法

我最终这样做了,这很有效:

class Settings {
    public int a;
    public String b;

    // 0 arg constructor uses the static defaults via the copy constructor
    public Settings() {
        this(Config.defaultSettings);
    }

    // copy constructor
    public Settings(Settings other) {
        // other will be null when creating the default settings
        if(other == null) return;

        // rest of copy constructor
    }
}

class Entry {
    public String name;
    public Settings settings = Config.defaultSettings; // use default if not set separately
}

class Config {
    public static Settings defaultSettings; // this is static
    public List<Entry> entries;

    // this is a setter that actually sets the static member
    public void setDefaultSettings(Settings defaultSettings) {
        Config.defaultSettings = defaultSettings);
}

然后是杰克逊:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Configuration config = mapper.readValue(configFile,Config.class);

本质上,这会设置一个静态的 Settings(假设 defaultSettings 在文件中首先出现)。在 yaml 中指定了部分设置块的情况下,设置 0-arg 构造函数将用于创建 Config.defaultSettings 的副本,然后 Jackson 使用文件中指定的任何内容对其进行修改。如果文件中没有 settingsEntry 块,则直接使用 Config.defaultSettings(通过 Entry 中的字段初始化)。还不错,胜过编写自定义解串器。

如果有人有更好的方法,我仍然很感兴趣。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。