Java enum reverse look-up best practice

前端 未结 7 691
感情败类
感情败类 2020-12-04 15:07

I saw it suggested on a blog that the following was a reasonable way to do a \"reverse-lookup\" using the getCode(int) in a Java enum:

public en         


        
相关标签:
7条回答
  • 2020-12-04 15:51

    Here is an Java 8 alternative (with unit test):

    // DictionarySupport.java :
    
    import org.apache.commons.collections4.Factory;
    import org.apache.commons.collections4.map.LazyMap;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public interface DictionarySupport<T extends Enum<T>> {
    
        @SuppressWarnings("unchecked")
        Map<Class<?>,  Map<String, Object>> byCodeMap = LazyMap.lazyMap(new HashMap(), (Factory) HashMap::new);
    
        @SuppressWarnings("unchecked")
        Map<Class<?>,  Map<Object, String>> byEnumMap = LazyMap.lazyMap(new HashMap(), (Factory) HashMap::new);
    
    
        default void init(String code) {
            byCodeMap.get(this.getClass()).put(code, this);
            byEnumMap.get(this.getClass()).put(this, code) ;
        }
    
        static <T extends Enum<T>> T getByCode(Class<T> clazz,  String code) {
            clazz.getEnumConstants();
            return (T) byCodeMap.get(clazz).get(code);
        }
    
        default <T extends Enum<T>> String getCode() {
            return byEnumMap.get(this.getClass()).get(this);
        }
    }
    
    // Dictionary 1:
    public enum Dictionary1 implements DictionarySupport<Dictionary1> {
    
        VALUE1("code1"),
        VALUE2("code2");
    
        private Dictionary1(String code) {
            init(code);
        }
    }
    
    // Dictionary 2:
    public enum Dictionary2 implements DictionarySupport<Dictionary2> {
    
        VALUE1("code1"),
        VALUE2("code2");
    
        private Dictionary2(String code) {
            init(code);
        }
    }
    
    // DictionarySupportTest.java:     
    import org.testng.annotations.Test;
    import static org.fest.assertions.api.Assertions.assertThat;
    
    public class DictionarySupportTest {
    
        @Test
        public void teetSlownikSupport() {
    
            assertThat(getByCode(Dictionary1.class, "code1")).isEqualTo(Dictionary1.VALUE1);
            assertThat(Dictionary1.VALUE1.getCode()).isEqualTo("code1");
    
            assertThat(getByCode(Dictionary1.class, "code2")).isEqualTo(Dictionary1.VALUE2);
            assertThat(Dictionary1.VALUE2.getCode()).isEqualTo("code2");
    
    
            assertThat(getByCode(Dictionary2.class, "code1")).isEqualTo(Dictionary2.VALUE1);
            assertThat(Dictionary2.VALUE1.getCode()).isEqualTo("code1");
    
            assertThat(getByCode(Dictionary2.class, "code2")).isEqualTo(Dictionary2.VALUE2);
            assertThat(Dictionary2.VALUE2.getCode()).isEqualTo("code2");
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题