
软件开发中常需处理常量及含义。魔法数字是编程反模式,难理解和维护。Java 枚举类型可消除魔法数字,实现数据与逻辑映射。本文探讨其用法、示例代码及实际价值。

定义枚举类 Color,有 RED、GREEN、BLUE 三个枚举常量,创建时关联字符串描述,通过自定义构造函数实现。
public enum Color {
RED("红"),
GREEN("绿"),
BLUE("蓝");
private String description;
// 构造函数私有化,确保枚举类型的实例只能通过预定义的枚举值创建
// 当你创建Color枚举类并定义其成员(RED、GREEN和BLUE)时,每个成员都有一个构造函数调用
// 这里的RED("红")、GREEN("绿")和BLUE("蓝")就是在实例化枚举成员时传入的参数
// 它们分别对应构造函数的参数String description:
Color(String description) {
this.description = description;
}
// 提供获取描述的方法
public String getDescription() {
return this.description;
}
}当需获取颜色对应的描述时,可调用 getDescription()方法。
public class EnumUsageExample {
public static void main(String[] args) {
System.out.println(Color.RED.getDescription()); // 输出:红
}
}Color.RED.getDescription()调用过程:
Color是枚举类型,有 RED、GREEN、BLUE 实例。Color.RED引用实例,创建时传描述字符串。getDescription()返回私有变量description值。Color.RED调用构造函数,后通过getDescription()返回“红”,description隐式设为对应字符串。程序中用数字 0 表红色、1 表绿色、2 表蓝色,易使其他开发者困惑且不便扩展修改。解决方案:用枚举将数字转换为有意义常量名。
public enum ColorCode {
RED(0),
GREEN(1),
BLUE(2);
private int code;
ColorCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static ColorCode fromCode(int code) {
for (ColorCode color : ColorCode.values()) {
if (color.getCode() == code) {
return color;
}
}
throw new IllegalArgumentException("Invalid color code");
}
}
// 使用枚举替换魔法数字
public class EnumAntiPatternExample {
public static void main(String[] args) {
int colorCode = 0;
ColorCode color = ColorCode.fromCode(colorCode);
System.out.println(color.name()); // 输出:RED
}
}示例中,枚举类型 ColorCode 取代数字表示颜色状态。枚举类有三个成员,各有整数代码。fromCode()是静态方法,根据整数代码找对应枚举值。主函数中,ColorCode.fromCode(0)找到对应颜色枚举(RED)并输出名称。
在某些情况需将枚举值映射到其他对象或数据结构。定义 Status 枚举,各枚举值有名称、关联外部系统状态码及用户友好描述。fromCode()方法接收状态码字符串参数,遍历枚举值找匹配实例。主函数中,Status.fromCode("active")找到对应枚举值(ACTIVE)并输出描述信息。
public enum Status {
ACTIVE("active", "启用"),
INACTIVE("inactive", "禁用");
private String code;
private String description;
Status(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return this.code;
}
public String getDescription() {
return this.description;
}
// 反向查找,根据code找到对应的枚举值
public static Status fromCode(String code) {
for (Status status : Status.values()) {
if (status.getCode().equals(code)) {
return status;
}
}
throw new IllegalArgumentException("Invalid status code");
}
}
// 使用映射关系
public class EnumMappingExample {
public static void main(String[] args) {
String statusCode = "active";
Status status = Status.fromCode(statusCode);
System.out.println(status.getDescription()); // 输出:启用
}
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。