枚举的4种使用方式

1.枚举实现单例模式

public class demo {
    public static void main(String[] args) {
        //1.枚举不带属性
        System.out.println(SignDocCType.FNA);               //FNA

        //2.枚举带一个属性
        System.out.println(SignDocType.FNA);                //FNA
        System.out.println(SignDocType.FNA.getValue());     //0

        //3.枚举带2个属性
        System.out.println(SignDocdType.AUDIO.getName());   //音频
        System.out.println(SignDocdType.AUDIO.getValue());  //2

        //4.通过枚举的属性匹配枚举
        System.out.println(FNAChoice2Value.AUDIO.getByValue(1));              //VIDEO
        System.out.println(FNAChoice2Value.IMAGE.getByValueAndName(4, "图像"));//IMAGE
    }
}

2.JAVA实现枚举

2.1 枚举不带属性

public enum SignDocCType {

    FNA, ECLARATION_FOR_INTERMEDIARIES, IFS_MP

}

2.2 枚举带一个属性(常用)

public enum SignDocType {

    FNA("0"), IFS_MP("3");

    //属性
    public String docType;

    //有参构造器
    SignDocType(String docType){
        this.docType = docType;
    }

    //get器
    public String getValue() {
        return docType;
    }

}

2.3 枚举带2个属性

public enum SignDocdType {
    VIDEO(1, "视频"), AUDIO(2, "音频"), TEXT(3, "文本"), IMAGE(4, "图像");

    //属性
    int value;
    String name;

    //有参构造器
    SignDocdType(int value, String name) {
        this.value = value;
        this.name = name;
    }

    //get器
    public int getValue() {
        return value;
    }

    public String getName() {
        return name;
    }
}

2.4 通过枚举的属性匹配枚举

@Getter
public enum FNAChoice2Value {
    VIDEO(1, "视频"), AUDIO(2, "音频"), TEXT(3, "文本"), IMAGE(4, "图像");

    int value;
    String name;

    FNAChoice2Value(int value, String name) {
        this.value = value;
        this.name = name;
    }

    //通过value找到对应的枚举
    public FNAChoice2Value getByValue(int value) {
        for(FNAChoice2Value typeEnum : FNAChoice2Value.values()) {
            if(typeEnum.value == value) {
                return typeEnum;
            }
        }
        //throw new IllegalArgumentException("No element matches " + value);
        return null;
    }

    //通过value和name找到枚举
    public FNAChoice2Value getByValueAndName(int value,String name) {
        for(FNAChoice2Value typeEnum : FNAChoice2Value.values()) {
            if(typeEnum.value == value && typeEnum.getName().equals(name)) {
                return typeEnum;
            }
        }
        return null;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_45450428/article/details/108214237