diff --git a/src/main/java/com/minelittlepony/settings/SensibleConfig.java b/src/main/java/com/minelittlepony/settings/SensibleConfig.java index 24e41b82..abc4f2aa 100644 --- a/src/main/java/com/minelittlepony/settings/SensibleConfig.java +++ b/src/main/java/com/minelittlepony/settings/SensibleConfig.java @@ -2,6 +2,12 @@ package com.minelittlepony.settings; import com.minelittlepony.common.client.gui.IField.IChangeCallback; +import javax.annotation.Nonnull; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + /** * A sensible config container that actually lets us programmatically index values by a key. * @@ -9,6 +15,7 @@ import com.minelittlepony.common.client.gui.IField.IChangeCallback; * */ // Mumfrey pls. +// TODO: Reflection public abstract class SensibleConfig { public abstract void save(); @@ -39,19 +46,55 @@ public abstract class SensibleConfig { } } + private Map entries = new HashMap<>(); + private Map fieldEntries = new HashMap<>(); + public boolean getValue(Setting key) { + return entries.computeIfAbsent(key, this::reflectGetValue); + } + + public boolean setValue(Setting key, boolean value) { + entries.put(key, value); try { - return getClass().getField(key.name().toLowerCase()).getBoolean(this); - } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) { + findField(getClass(), key).setBoolean(this, value); + } catch (IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + } + + return value; + } + + @Nonnull + protected Field findField(Class type, Setting key) { + return fieldEntries.computeIfAbsent(key, k -> recurseFindField(type, key)); + } + + private boolean reflectGetValue(Setting key) { + try { + return findField(getClass(), key).getBoolean(this); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { + e.printStackTrace(); + return true; } } - public boolean setValue(Setting key, boolean value) { + @Nonnull + private Field recurseFindField(Class type, Setting key) { try { - getClass().getField(key.name().toLowerCase()).setBoolean(this, value); - } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) { + Field f = type.getDeclaredField(key.name().toLowerCase()); + f.setAccessible(true); + fieldEntries.put(key, f); + + return f; + } catch (IllegalArgumentException | NoSuchFieldException | SecurityException e) { + Class superType = type.getSuperclass(); + + if (superType != null && superType != Object.class) { + return recurseFindField(superType, key); + } + + throw new RuntimeException(String.format("Config option %s was not defined", key), e); } - return value; } }