Java枚举是独立引用类型,编译为final类继承Enum,具备类型安全、序列化支持和switch语义检查;必须用enum关键字定义,常量首行声明,构造器私有且隐式final,实例唯一且不可反射创建。

Java 中的 Enum 不是“类的简写版”,而是独立的引用类型,编译后生成 final 类并继承 java.lang.Enum;直接用 class 模拟枚举会丢失类型安全、序列化支持和 switch 语义检查。
定义枚举:必须用 enum 关键字,不能用 class
枚举常量必须在第一行显式列出,后跟分号(可选),之后才能定义字段、构造器或方法:
public enum HttpStatus {
OK(200, "OK"),
NOT_FOUND(404, "Not Found"),
INTERNAL_ERROR(500, "Internal Server Error");
private final int code;
private final String reason;
HttpStatus(int code, String reason) {
this.code = code;
this.reason = reason;
}
public int getCode() { return code; }
public String getReason() { return reason; }
}
- 构造器必须是
private(省略也默认私有) - 每个常量调用构造器时,参数必须匹配且不可省略(哪怕全为
null) - 枚举类隐式
final,不能被继承 - 不能有
public或protected构造器,否则编译报错:Illegal modifier for the enum constructor
使用枚举值:通过常量名直接引用,不 new,不反射
枚举实例在类加载时就已创建完毕,全局唯一:
HttpStatus status = HttpStatus.OK; System.out.println(status.getCode()); // 200 System.out.println(status.name()); // "OK" System.out.println(status.ordinal()); // 0(声明顺序索引)
-
name()返回声明时的字面量(不是toString()),不可覆盖;覆盖toString()只影响打印,不影响name() -
valueOf(String)严格匹配name(),大小写敏感,不存在则抛IllegalArgumentException - 不要用
new HttpStatus(...)—— 编译失败;也不要试图用Class.newInstance()创建新实例 —— 运行时报NoSuchMethodException(无公有构造器)
在 switch 中使用枚举:编译期检查 + 避免字符串硬编码
Java 7+ 支持 enum 直接用于 switch,编译器能检查是否遗漏分支(配合 default 或 IDE 警告):
立即学习“Java免费学习笔记(深入)”;
switch (status) {
case OK:
handleSuccess();
break;
case NOT_FOUND:
handle404();
break;
default:
throw new IllegalStateException("Unexpected status: " + status);
}
- case 后只能写枚举常量名(如
OK),不能写HttpStatus.OK或字符串 - IDE 通常能提示未覆盖的枚举值(尤其开启
Missing enum constant in switch检查时) - 相比
if (status.equals("OK")),这里类型安全、无拼写错误风险、无空指针隐患
反序列化与 JSON 处理:注意 name() 和自定义字段的映射差异
多数 JSON 库(如 Jackson)默认按 name() 序列化枚举;若需输出 code 或 reason,必须显式配置:
// Jackson 示例:用 @JsonValue 指定序列化字段
public enum HttpStatus {
OK(200, "OK");
private final int code;
HttpStatus(int code, String reason) { this.code = code; }
@JsonValue public int getCode() { return code; } // 输出数字而非 "OK"
}
- 反序列化时,默认仍按
name()匹配;若 JSON 是数字(如200),需用@JsonCreator+ 静态工厂方法 - 不要依赖
toString()做序列化 —— 它不是契约方法,可能被随意重写 - 枚举的
readObject被 JVM 特殊处理,无法通过普通反序列化伪造新实例,安全性比普通类高
枚举的真正复杂点不在语法,而在于它把「实例唯一性」「编译期约束」「JVM 级别保护」绑在一起;一旦试图绕过 enum 关键字、或用反射强行修改 values() 缓存,就会触发底层机制报错或行为异常。










