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

本文详细介绍了Java中的枚举类型,解释了为什么枚举只允许使用预定义的枚举常量,并通过一个颜色选择器的例子展示了如何使用枚举配合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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值