All Downloads are FREE. Search and download functionalities are using the official Maven repository.

generator.server.javatool.enums.main.Enums.mustache Maven / Gradle / Ivy

There is a newer version: 1.22.0
Show newest version
package {{ packageName }}.shared.enumeration.domain;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import {{ packageName }}.shared.error.domain.Assert;

public final class Enums {

  private static final EnumMappings MAPPINGS = new EnumMappings();

  private Enums() {}

  public static , To extends Enum> To map(Enum from, Class to) {
    Assert.notNull("to", to);

    if (from == null) {
      return null;
    }

    return MAPPINGS.get(from, to);
  }

  private static final class EnumMappings {

    private final Map, Map, Enum>> cache = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    private , To extends Enum> To get(Enum from, Class to) {
      return (To) cache.computeIfAbsent(new CacheKey<>(from.getClass(), to), buildCache(from)).get(from);
    }

    @SuppressWarnings("unchecked")
    private > Function, Map, Enum>> buildCache(Enum from) {
      return key -> {
        try {
          return Arrays.stream(key.from().getEnumConstants()).collect(
            Collectors.toMap(Function.identity(), source -> Enum.valueOf(key.to(), source.name()))
          );
        } catch (IllegalArgumentException e) {
          throw new UnmappableEnumException(from.getClass(), key.to());
        }
      };
    }

    private record CacheKey, To extends Enum>(Class from, Class to) {}
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy