CustomEnumValueSerializer.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package com.gmail.nossr50.config.hocon;
  2. import com.google.common.reflect.TypeToken;
  3. import ninja.leaping.configurate.ConfigurationNode;
  4. import ninja.leaping.configurate.objectmapping.ObjectMappingException;
  5. import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer;
  6. import ninja.leaping.configurate.util.EnumLookup;
  7. import org.checkerframework.checker.nullness.qual.NonNull;
  8. import org.checkerframework.checker.nullness.qual.Nullable;
  9. import java.util.Optional;
  10. public class CustomEnumValueSerializer implements TypeSerializer<Enum> {
  11. @Override
  12. @SuppressWarnings("unchecked") // i continue to hate generics
  13. public Enum deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException {
  14. String enumConstant = HOCONUtil.deserializeENUMName(value.getString());
  15. if (enumConstant == null) {
  16. throw new ObjectMappingException("No value present in node " + value);
  17. }
  18. Optional<Enum> ret = (Optional) EnumLookup.lookupEnum(type.getRawType().asSubclass(Enum.class),
  19. enumConstant); // XXX: intellij says this cast is optional but it isnt
  20. if (!ret.isPresent()) {
  21. throw new ObjectMappingException("Invalid enum constant provided for " + value.getKey() + ": " +
  22. "Expected a value of enum " + type + ", got " + enumConstant);
  23. }
  24. return ret.get();
  25. }
  26. @Override
  27. public void serialize(@NonNull TypeToken<?> type, @Nullable Enum obj, @NonNull ConfigurationNode value) throws ObjectMappingException {
  28. value.setValue(HOCONUtil.serializeENUMName(obj.name()));
  29. }
  30. }