EnumMapperType 인터페이스 - enum이 구현해야할 공통 인터페이스
public interface EnumMapperType{
String getCode();
String getTitle();
}
Enum 클래스 정의
public enum Club implements EnumMapperType{
CENTER("중앙동아리"),
SMALL("소모임");
private final String title;
@Override
public String getCode(){
return name();
}
EnumMapper - enum들을 관리해주는 메서드를 정의한 클래스
public class EnumMapper{
private Map<String, List<EnumMapperValue>> factory = new HashMap<>();
public void put(String key, Class<? extends EnumMapperValue> e) {
factory.put(key, toEnumValues(e));
}
public List<EnumMapperValue> get(String key) {
return factory.get(key);
}
private List<EnumMapperValue> toEnumValues(Class<? extends EnumMapperValue> e) {
return Stream.of(e.getEnumConstants()).map(EnumMapperValue.class::cast).collect(Collectors.toList());
}
public Map<String, List<EnumMapperValue>> getAll() {
return factory;
}
}
EnumConfig - Factory에 enum등록해줌
public class EnumConfig{
@Bean
public EnumMapper getEnumMapper(){
EnumMapperFactory enumMapperFactory=new EnumMapperFactory(new LinkedHashMap<>());
enumMapperFactory.put("Club",Club.class):
return enumMapperFactory;
EnumMapperValue - EnumMapperType을 implements한 구현체에 대해 실제값을 가지는 클래스
@Getter
public class EnumMapperValue{
private String code;
private String title;
public EnumMapperValue(EnumMapperType enumMapperType){
code=enumMapperType.getCode();
title=enumMapperType.getTitle();
}
}
실제 사용
public class EnumExample{
public static void main(String[] args){
EnumMapperValue CenterValue=new EnumMapperValue(Club.CENTER);
EnumMapperValue SmallValue=new EnumMapperValue(Club.SMALL);
}
references
https://mangkyu.tistory.com/74