杰瑞科技汇

Java enum 如何转为 int?

在 Java 中,将 enum 转换为 int 有多种方法,最常用的是利用 enumordinal() 方法或为 enum 显式定义 int 值,以下是几种常见的方式:

Java enum 如何转为 int?-图1
(图片来源网络,侵删)

方法 1:使用 ordinal()(不推荐)

enum 默认有一个 ordinal() 方法,返回枚举常量的序号(从 0 开始)。

public enum Color {
    RED, GREEN, BLUE;
}
public class Main {
    public static void main(String[] args) {
        int redInt = Color.RED.ordinal(); // 返回 0
        int greenInt = Color.GREEN.ordinal(); // 返回 1
        int blueInt = Color.BLUE.ordinal(); // 返回 2
    }
}

缺点

  • 依赖枚举的声明顺序,修改顺序会导致 int 值变化,不够健壮。
  • 不适用于需要自定义 int 值的场景。

方法 2:显式定义 int 值(推荐)

可以为 enum 成员直接分配 int 值,然后通过方法获取。

示例 1:直接赋值

public enum Color {
    RED(1),
    GREEN(2),
    BLUE(3);
    private final int value;
    Color(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
}
public class Main {
    public static void main(String[] args) {
        int redInt = Color.RED.getValue(); // 返回 1
        int greenInt = Color.GREEN.getValue(); // 返回 2
    }
}

示例 2:使用 switchif-else 转换

如果不想为每个枚举定义字段,可以用 switch 转换:

Java enum 如何转为 int?-图2
(图片来源网络,侵删)
public enum Color {
    RED, GREEN, BLUE;
}
public class Main {
    public static int colorToInt(Color color) {
        switch (color) {
            case RED: return 1;
            case GREEN: return 2;
            case BLUE: return 3;
            default: throw new IllegalArgumentException("Unknown color");
        }
    }
    public static void main(String[] args) {
        int redInt = colorToInt(Color.RED); // 返回 1
    }
}

方法 3:使用 EnumMapHashMap(灵活)

如果需要更灵活的映射关系,可以用 Map 存储 enumint 的对应关系。

import java.util.HashMap;
import java.util.Map;
public enum Color {
    RED, GREEN, BLUE;
}
public class Main {
    private static final Map<Color, Integer> COLOR_MAP = new HashMap<>();
    static {
        COLOR_MAP.put(Color.RED, 1);
        COLOR_MAP.put(Color.GREEN, 2);
        COLOR_MAP.put(Color.BLUE, 3);
    }
    public static int getColorInt(Color color) {
        return COLOR_MAP.getOrDefault(color, -1); // 默认返回 -1 表示未找到
    }
    public static void main(String[] args) {
        int redInt = getColorInt(Color.RED); // 返回 1
    }
}

方法 4:使用 @JsonValue(Jackson JSON 序列化)

如果需要将 enum 序列化为 int(如 JSON),可以用 Jackson 的 @JsonValue 注解:

import com.fasterxml.jackson.annotation.JsonValue;
public enum Color {
    RED(1),
    GREEN(2),
    BLUE(3);
    private final int value;
    Color(int value) {
        this.value = value;
    }
    @JsonValue  // 标记此方法用于序列化
    public int getValue() {
        return value;
    }
}

使用场景:在 JSON API 中返回 enum 时自动转为 int


方法 适用场景 优点 缺点
ordinal() 简单场景,无需自定义值 无需额外代码 依赖声明顺序,不灵活
显式定义 int 推荐,需固定映射 健壮、可控 需要额外字段和方法
switch/if-else 逻辑简单,无需存储 直接明了 代码冗长
Map 映射 动态或复杂映射 灵活 需要额外存储
@JsonValue JSON 序列化 自动转换 仅限 Jackson

推荐

  • 大多数情况下,显式定义 int 值(方法 2) 是最清晰和健壮的方式。
  • 如果需要动态映射,用 Map(方法 3)。
  • 避免 ordinal(),除非你完全控制枚举顺序。
分享:
扫描分享到社交APP
上一篇
下一篇