String 类型实例的 enum 配合 switch 使用的一个小例子

An enum type has no instances other than those defined by its enum
constants. It is a compile-time error to attempt to explicitly
instantiate an enum type
(§15.9.1).

Java 中的枚举类型是一种特殊的类,其中的值都是特殊的一些实例。枚举只有它自己定义好的实例,也就是枚举常量,任何想要另外显式进行枚举实例化的操作都不会被编译器所接受。
在参数只能从一个小量的固定值的集合中取值的时候,应始终使用枚举。将枚举作为参数能够将一些运行期的检查提升至编译期执行,进而避免掉一些运行时错误。同时,你还将可以合法使用的值进行了编程式的文档化。
本文以一段颜色选用的代码,演示了一个 enum 配合 switch 进行使用的示例。
enum 定义:

public enum SuportedColors {
    GRAY("GRAY"),
    GREEN("GREEN"),
    YELLOW("YELLOW"),
    ORANGE("ORANGE"),
    RED("RED");
    private String capacityStatusColor;
    SuportedColors(String capacityStatusColor) {
        this.capacityStatusColor = capacityStatusColor;
    }
    public String getCapacityStatusColor() {
        return capacityStatusColor;
    }
    public static SuportedColors getByValue(String capacityStatusColor) {
        for (SuportedColors suportedColors : values()) {
            if (suportedColors.getCapacityStatusColor().equalsIgnoreCase(capacityStatusColor)) {
                return suportedColors;
            }
        }
        return null;
    }
}

使用 enum 的地方:

import java.awt.Color;
...
    SuportedColors suportedColors = SuportedColors.getByValue(currRowModel.getCaSpaceStatusColor());
    if (null != suportedColors) {
        switch (suportedColors) {
            case GRAY: {
                return Color.GRAY;
            }
            case GREEN: {
                return Color.GREEN;
            }
            case YELLOW: {
                return Color.YELLOW;
            }
            case ORANGE: {
                return Color.ORANGE;
            }
            case RED: {
                return Color.RED;
            }
        }
    }

参考资料

What are enums and why are they useful?

posted @ 2018-08-02 14:28  Defonds  阅读(35)  评论(0编辑  收藏  举报