[utils] get EnumUtil tool class of enumeration through a field value in enumeration

Keywords: encoding

Sometimes, in this case, we have the value of one of the enumeration fields, and then get the information of enumeration or other fields through this value. If there is no tool class, we need to add corresponding methods to each enumeration. Through the method of tool class, we can reduce the code generation and make it more concise and beautiful

Create an interface CommonEnum

/**
 * Enumeration interface
 */
public interface CommonEnum {

    int getValue();

}

Enumeration implements this interface

/**
 * Status enumeration
 */
public enum StatusEnum implements CommonEnum {

    WAITTING(0, "WAITTING", "wait for"),
    STARTED(1, "STARTED", "start"),
    END(2, "END", "End");

    private int code;
    private String name;
    private String desc;

    StatusEnum(int code, String name, String desc) {
        this.code = code;
        this.name = name;
        this.desc = desc;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public int getValue() {
        return code; //Get the enumeration according to what value you need, and return what value here
    }
}

Tool class EnumUtil

/**
 * Enumeration tool class
 */
public class EnumUtil {

    /**
     * Returns the 'enumeration' of the specified encoding
     * @param code
     * @return SharedObjTypeEnum
     * @throws
     */
    public static <T extends CommonEnum> T getEnumBycode(Class<T> clazz, int code) {
        for(T _enum : clazz.getEnumConstants())
            if(code == _enum.getValue())
                return _enum;
        return null;
    }

}

usage method

StatusEnum statusEnum = EnumUtil.getEnumBycode(StatusEnum.class, 1);

Posted by Dysan on Sun, 10 May 2020 07:47:56 -0700