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 警告):