java 使用 enum(枚举)


枚举的使用

  • 枚举类的理解:类的对象只有有限个,确定的。我们称此类为枚举类
  • 当需要定义一组常量时,强烈建议使用枚举类
  • 如果枚举类中只有一个对象,则可以作为单例模式的实现方式。

枚举的属性

  • 枚举类对象的属性不应允许被改动,所以应该使用 private final 修饰
  • 枚举类的使用 private final 修饰的属性应该在构造器中为其赋值
  • 若枚举类显式的定义了带参数的构造器,则在列出枚举值时也必须对应的传入参数

测试

package com.test;

/**
 * @author z
 */
public class Test {
    public static void main(String[] args) {
        // code
        System.out.println(MyEnums.MY_TEST_ONE.getCode());
        // value
        System.out.println(MyEnums.MY_TEST_ONE.getValue());
        // 获取变量名列表
        for(MyEnums myEnums:MyEnums.getVariables()){
            System.out.println(myEnums.toString());
        }
        // 根据 key 获取 value
        System.out.println(MyEnums.getValue(2));
    }
}
public enum MyEnums{
    MY_TEST_ONE(1,"测试1"),
    MY_TEST_TWO(2,"测试2"),
    MY_TEST_three(3,"测试3"),
    ;
    private final int code;
    private final String value;
    MyEnums(int code,String value){
        this.code=code;
        this.value=value;
    }

    /**
     * 获取 code
     */
    public int getCode(){
        return this.code;
    }

    /**
     * 获取 value
     */
    public String getValue(){
        return this.value;
    }

    /**
     * 获取变量名列表
     */
    public static MyEnums[] getVariables(){
        return values();
    }

    /**
     * 根据code获取value
     */
    public static String getValue(int code){
        for(MyEnums myEnums:values()){
            if(code==myEnums.code){
                return myEnums.value;
            }
        }
        return "";
    }
}

结果: