diff --git a/ConfigLib-Core/src/main/java/de/exlll/configlib/Configuration.java b/ConfigLib-Core/src/main/java/de/exlll/configlib/Configuration.java index 636559d..fc341c7 100644 --- a/ConfigLib-Core/src/main/java/de/exlll/configlib/Configuration.java +++ b/ConfigLib-Core/src/main/java/de/exlll/configlib/Configuration.java @@ -46,6 +46,7 @@ public abstract class Configuration { String dump = new ConfigurationReader(configPath).read(); Map valuesByFieldNames = YamlSerializer.deserialize(dump); fieldMapper.mapValuesToFields(valuesByFieldNames, this); + postLoadHook(); } /** @@ -81,9 +82,16 @@ public abstract class Configuration { save(); } catch (NoSuchFileException e) { save(); + postLoadHook(); } } + /** + * Can be overridden to do something after all fields have been loaded. + */ + protected void postLoadHook() { + } + private void createParentDirectories() throws IOException { Files.createDirectories(configPath.getParent()); } diff --git a/ConfigLib-Core/src/test/java/de/exlll/configlib/ConfigurationTest.java b/ConfigLib-Core/src/test/java/de/exlll/configlib/ConfigurationTest.java index f774b75..ea49bde 100644 --- a/ConfigLib-Core/src/test/java/de/exlll/configlib/ConfigurationTest.java +++ b/ConfigLib-Core/src/test/java/de/exlll/configlib/ConfigurationTest.java @@ -81,6 +81,45 @@ public class ConfigurationTest { assertThat(Files.exists(filePath), is(true)); } + @Test + public void postLoadHookExecutedAfterLoad() throws Exception { + HookTestClass cls = new HookTestClass(filePath); + cls.save(); + assertThat(cls.hookCalled, is(false)); + cls.load(); + assertThat(cls.hookCalled, is(true)); + } + + @Test + public void postLoadHookExecutedAfterLoadAndSaveIfPathNotExists() throws Exception { + HookTestClass cls = new HookTestClass(filePath); + assertThat(cls.hookCalled, is(false)); + cls.loadAndSave(); + assertThat(cls.hookCalled, is(true)); + } + + @Test + public void postLoadHookExecutedAfterLoadAndSaveIfPathExists() throws Exception { + HookTestClass cls = new HookTestClass(filePath); + cls.save(); + assertThat(cls.hookCalled, is(false)); + cls.loadAndSave(); + assertThat(cls.hookCalled, is(true)); + } + + private static final class HookTestClass extends Configuration { + private transient boolean hookCalled; + + public HookTestClass(Path configPath) { + super(configPath); + } + + @Override + protected void postLoadHook() { + hookCalled = true; + } + } + private static final class OriginalTestClass extends Configuration { private int a = 0; private int b = 1;