Skip to content

Instantly share code, notes, and snippets.

@Elyorbe
Created July 31, 2025 06:39
Show Gist options
  • Save Elyorbe/9f639b92edd5ca52a0333d7aab501a01 to your computer and use it in GitHub Desktop.
Save Elyorbe/9f639b92edd5ca52a0333d7aab501a01 to your computer and use it in GitHub Desktop.
Enum type commonization
import java.util.Optional;
public interface EnumType {
String getCode();
String getDescription();
static <E extends Enum<E> & EnumType> Optional<E> fromCode(Class<E> enumType, String code) {
return EnumValueResolver.fromCode(enumType, code);
}
}
import java.util.List;
import java.util.Optional;
public class EnumTypeUsage {
public static void main(String[] args) {
Optional<ServiceType> dosAdminServiceType = EnumType.fromCode(ServiceType.class, "DOS_ADMIN");
dosAdminServiceType.ifPresent(serviceType -> System.out.println("dosAdminServiceType description: " + serviceType.getDescription()));
Optional<StaffStatus> deletedStaffStatus = EnumType.fromCode(StaffStatus.class, "DELETED");
deletedStaffStatus.ifPresent(staffStatus -> System.out.println("deletedStaffStatus description: " + staffStatus.getDescription()));
Optional<StaffStatus> invalidStatus = EnumType.fromCode(StaffStatus.class, "invalidCode");
assert invalidStatus.isEmpty();
// Doesn't compile
//EnumType.fromCode(List.class, "invalid code");
}
}
import static java.util.Arrays.stream;
import static java.util.function.UnaryOperator.identity;
import static java.util.stream.Collectors.toMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* For internal use only.
* <p>
* Use the {@link EnumType#fromCode(Class, String)} instead
* </p>
*/
final class EnumValueResolver {
private static final Map<Class<?>, Map<String, ? extends EnumType>> CACHE = new ConcurrentHashMap<>();
private EnumValueResolver() {}
@SuppressWarnings("unchecked")
static <E extends Enum<E> & EnumType> Optional<E> fromCode(Class<E> enumType, String code) {
E value = (E) CACHE.computeIfAbsent(enumType, key -> stream(enumType.getEnumConstants())
.collect(toMap(E::getCode, identity()))).get(code);
return Optional.ofNullable(value);
}
}
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
@Schema(description = "시스템 구분")
public enum ServiceType implements EnumType {
DOS_ADMIN("DOS_ADMIN", "DOS Admin service"),
DOS_USER("DOS_USER", "DOS User service");
private final String code;
private final String description;
}
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
@Schema(description = "거래상태")
public enum StaffStatus implements EnumType {
INITIALIZED("INITIALIZED", "초기 상태"),
DELETED("DELETED", "삭제");
private final String code;
private final String description;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment