Skip to content

1.x Basics

Guillaume R edited this page Apr 29, 2018 · 5 revisions

The Config interface

The Config interface is central in NightConfig. It represents a configuration that contains key/value entries.

Paths

A config entry is uniquely identified by its path, which gives its key and the names of its parents (if any). A path is usually written as a String with dots used to separate its different parts.

For instance, consider the following HOCON configuration:

number: 123
sub {
    boolean: true
}

We have the following path/value mapping:

Path (as a dot-separated String) Value
number 123
sub {boolean: true}
sub.boolean true
boolean does not exist

Config methods

The methods of the Config interface have pretty obvious names. Here are the most important ones:

  • getValue(path) returns a value, or null if not found.
  • getOptionalValue(path) returns a value, or Optional.empty() if not found. You can then use all the power of Optional!
String str = config.getOptionalValue("myString").orElse("defaultValue");// Gets a default value if no one exist in the config
config.getOptionalValue("myValue").ifPresent(value -> useTheValue(value));// Uses the value only if it exists and isn't null
  • setValue(path, value) sets a value. Depending on the type of the config, some values might be rejected (but it's generally not the case, read the javadoc for more infos).
  • removeValue(path) obviously removes a value.
  • containsValue(path) obviously checks if a value exists.
  • asMap() returns a Map<String, Object> that is linked to the config. It contains all the config's entries and any change in the Map is reflected in the config.

The path argument can be a String (dot-separated) or a List<String> (useful when the entry's name contains dots).

Config implementations

NightConfig version 1 provides 6 concrete implementations of the Config interface:

  • One per supported config type: JsonConfig, HoconConfig, TomlConfig, YamlConfig
  • An in-memory config: SimpleConfig
  • A wrapper around another config: CheckedConfig. It ensures that only valid values are put into the config, and throw an Exception when it's not the case; whereas the Json, Hocon, Toml and Yaml configs don't perform any check.