|
| 1 | +package pl.mikigal.config.serializer.java; |
| 2 | + |
| 3 | +import pl.mikigal.config.BukkitConfiguration; |
| 4 | +import pl.mikigal.config.exception.InvalidConfigException; |
| 5 | +import pl.mikigal.config.serializer.Serializer; |
| 6 | + |
| 7 | +import java.lang.reflect.InvocationTargetException; |
| 8 | +import java.lang.reflect.Method; |
| 9 | + |
| 10 | +/** |
| 11 | + * Built-in serializer for Enums |
| 12 | + * @see Enum |
| 13 | + * @see Serializer |
| 14 | + * @since 1.2.6 |
| 15 | + * @author Mikołaj Gałązka |
| 16 | + */ |
| 17 | +public class EnumSerializer extends Serializer<Enum> { |
| 18 | + |
| 19 | + @Override |
| 20 | + protected void saveObject(String path, Enum object, BukkitConfiguration configuration) { |
| 21 | + configuration.set(path + ".value", object.toString()); |
| 22 | + configuration.set(path + ".type", object.getClass().getName()); |
| 23 | + } |
| 24 | + |
| 25 | + @Override |
| 26 | + public Enum deserialize(String path, BukkitConfiguration configuration) { |
| 27 | + String value = configuration.getString(path + ".value"); |
| 28 | + String classPath = configuration.getString(path + ".type"); |
| 29 | + Class<?> clazz; |
| 30 | + Method valueOfMethod; |
| 31 | + |
| 32 | + try { |
| 33 | + clazz = Class.forName(classPath); |
| 34 | + valueOfMethod = clazz.getMethod("valueOf", String.class); |
| 35 | + } catch (ClassNotFoundException | NoSuchMethodException e) { |
| 36 | + throw new RuntimeException("An error occurred while deserializing class '" + classPath + "'", e); |
| 37 | + } |
| 38 | + |
| 39 | + try { |
| 40 | + return (Enum<?>) valueOfMethod.invoke(null, value); |
| 41 | + } catch (IllegalAccessException | InvocationTargetException e) { |
| 42 | + throw new InvalidConfigException("Value " + value + " is not valid for type " + classPath, e); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments