JAVA中定义常量的3种方式

1、最古老的

 //未处理
public static final int PROCESS_STATUS_UNTREATED = 0;
//已接收
public static final int PROCESS_STATUS_ACCPECTED = 1;
//已处理
public static final int PROCESS_STATUS_PROCESSED = 2;

2、改进版的

public static final class PROCESS_STATUS{
        //未处理
        public static final int UNTREATED = 0;
        //已接收
        public static final int ACCPECTED = 1;
        //已处理
        public static final int PROCESSED = 2;
}

3、枚举版(好处显而易见,既可以获取code又能获取汉字),以后定义常量采用此方法

public static enum PROCESS_STATUS implements KeyValueEnum{
        UNTREATED(0,"未处理"),
        ACCPECTED(1,"已接收"),
        PROCESSED(2,"已处理");
        private Integer code;
        private String desc;
        private PROCESS_STATUS(Integer key , String value){
            this.code = key;
            this.desc = value;
        }
        @Override
        public Integer getCode() {
            return code;
        }

        @Override
        public String getDesc() {
            return desc;
        }   
    }

 调用方式:

//获取编码
PROCESS_STATUS.UNTREATED.getCode();
//获取描述
PROCESS_STATUS.UNTREATED.getDes();

 根据枚举类型和编码获取code的描述:

 public static <T extends Enum<T> & KeyValueEnum>  String getEnumValue(Class<T> clazz ,
            Object codeValue) {
        String result = null;
        T[] enums = clazz.getEnumConstants();
        for(T obj : enums){
            if(obj.getCode().equals(codeValue)){
                result = String.valueOf(obj.getDesc());
                break;
            }
        }
        return result;
    }

 

你可能感兴趣的:(java)