1 枚举的一般使用
1.1 代替public static final
public enum RoleEnum {
USER, MANAGER, ADMIN
}
使用:
public static void main(String[] args) {
System.out.println(RoleEnum.MANAGER);
}
输出:
1.2 自定义字段
public enum RoleEnum {
USER("user"), MANAGER("manager"), ADMIN("admin");
String role;
RoleEnum(String role) {
this.role = role;
}
@Override
public String toString() {
return this.role;
}
}
使用:
public static void main(String[] args) {
System.out.println(RoleEnum.MANAGER);
}
输出:
2 枚举实现单例模式
public enum SingletonInstance {
INSTANCE;
public static SingletonInstance getInstance() {
return INSTANCE;
}
}
测试:
public static void main(String[] args) {
System.out.println(SingletonInstance.getInstance() == SingletonInstance.getInstance());
}
输出:
3 枚举反编译
3.1 反编译源码
public class Test {
public static void main(String[] args) {
System.out.println(RoleEnum.MANAGER);
}
}
enum RoleEnum {
USER, MANAGER, ADMIN
}
3.2 进行反编译
C:\gitTest>javac Test.java
C:\gitTest>java Test
MANAGER
C:\Users\17122\Desktop\gitTest>javap -p RoleEnum.class
Compiled from "Test.java"
final class RoleEnum extends java.lang.Enum<RoleEnum> {
public static final RoleEnum USER;
public static final RoleEnum MANAGER;
public static final RoleEnum ADMIN;
private static final RoleEnum[] $VALUES;
public static RoleEnum[] values();
public static RoleEnum valueOf(java.lang.String);
private RoleEnum();
static {};
}
3.3 结果及分析
final class RoleEnum extends java.lang.Enum<RoleEnum> {
public static final RoleEnum USER;
public static final RoleEnum MANAGER;
public static final RoleEnum ADMIN;
private static final RoleEnum[] $VALUES;
public static RoleEnum[] values();
public static RoleEnum valueOf(java.lang.String);
private RoleEnum();
static {};
}
由此可见:
- 枚举其实就是将类继承java.lang.Enum,每一个属性都是自身的对象类型。
- 生成了$VALUES字段,用于保存枚举类定义的枚举常量。
- valueOf方法进行值的类型转换