Fixed saving/loading of options

This commit is contained in:
Sollace 2019-05-30 18:06:51 +02:00
parent a2b7836a2e
commit 2fd94f9434

View file

@ -2,6 +2,12 @@ package com.minelittlepony.settings;
import com.minelittlepony.common.client.gui.IField.IChangeCallback; 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. * 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. // Mumfrey pls.
// TODO: Reflection
public abstract class SensibleConfig { public abstract class SensibleConfig {
public abstract void save(); public abstract void save();
@ -39,19 +46,55 @@ public abstract class SensibleConfig {
} }
} }
private Map<Setting, Boolean> entries = new HashMap<>();
private Map<Setting, Field> fieldEntries = new HashMap<>();
public boolean getValue(Setting key) { public boolean getValue(Setting key) {
return entries.computeIfAbsent(key, this::reflectGetValue);
}
public boolean setValue(Setting key, boolean value) {
entries.put(key, value);
try { try {
return getClass().getField(key.name().toLowerCase()).getBoolean(this); findField(getClass(), key).setBoolean(this, value);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) { } 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; return true;
} }
} }
public boolean setValue(Setting key, boolean value) { @Nonnull
private Field recurseFindField(Class<?> type, Setting key) {
try { try {
getClass().getField(key.name().toLowerCase()).setBoolean(this, value); Field f = type.getDeclaredField(key.name().toLowerCase());
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) { 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;
} }
} }