列舉工具類

小小開發發表於2018-08-24
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class EnumHelper implements Serializable {

    private static final long serialVersionUID = 5L;
    private static final String GET_CODE_METHOD = "getCode";
    private static final String GET_LABEL_METHOD = "getText";
    private static final Logger LOGGER = LoggerFactory.getLogger(EnumHelper.class);

    private EnumHelper() {
    }

    public static <T extends Enum<T>> List<T> inspectConstants(final Class<T> clazz) {
        return new ArrayList<T>(Arrays.asList(clazz.getEnumConstants()));
    }

    public static <T extends Enum<T>> List<T> inspectConstants(
            final Class<T> clazz, boolean containsNull) {
        List<T> list =
                new ArrayList<T>(Arrays.asList(clazz.getEnumConstants()));
        if (!containsNull) {
            list.remove(0);
        }
        return list;
    }

    public static <T extends Enum<T>> T translate(final Class<T> clazz,final String code) {
        if (code == null) {
            return null;
        }
        try {
            final Method m = clazz.getDeclaredMethod(GET_CODE_METHOD);
            for (T t : inspectConstants(clazz)) {
                if (code.equals(m.invoke(t))) {
                    return t;
                }
            }
        } catch (Exception e) { // NOSONAR
            LOGGER.error("failed to translate code {} into object of type {}",
                    code, clazz);
        }

        return null;
    }

    public static <T extends Enum<T>> String getCode(final T obj) {
        if (obj == null) {
            return null;
        }
        try {
            Class<?> clazz = obj.getClass();
            final Method m = clazz.getDeclaredMethod(GET_CODE_METHOD);
            return m.invoke(obj).toString();
        } catch (Exception e) { // NOSONAR
            // ignore
        }
        return null;
    }

    public static <T extends Enum<T>> T translateByLabel(final Class<T> clazz,final String label) {
        if (label == null) {
            return null;
        }
        try {
            final Method m = clazz.getDeclaredMethod(GET_LABEL_METHOD);
            for (T t : inspectConstants(clazz)) {
                if (label.equals(m.invoke(t))) {
                    return t;
                }
            }
        } catch (Exception e) { // NOSONAR
            // ignore
            LOGGER.error("failed to translate label {} into object of type {}",label, clazz);
        }
        return null;
    }

}
複製程式碼

相關文章