Enum的真正面目
Posted 一楼的开水瓶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Enum的真正面目相关的知识,希望对你有一定的参考价值。
一直想写一下关于java中枚举的东西
首先我们看这样一个类
public enum SeasonEnum {
SPRING("春天", "春暖花开"),
SUMMER("夏天", "炎炎盛夏"),
FALL("秋天", "秋高气爽"),
WINTER("冬天", "大雪纷飞");
private final String name;
private final String desc;
private SeasonEnum(String name, String desc) {
this.name = name;
this.desc = desc;
}
public static void main(String[] args) {
System.out.println(SeasonEnum.SPRING);
for(SeasonEnum s : SeasonEnum.values()){
System.out.println(s);
}
}
}
我们对齐用javac编译再用javap反编译看看
public final class com.xxxx.SeasonEnum extends java.lang.Enum<com.xxxx.SeasonEnum> {
public static final com.xxxx.SeasonEnum SPRING;
public static final com.xxxx.SeasonEnum SUMMER;
public static final com.xxxx.SeasonEnum FALL;
public static final com.xxxx.SeasonEnum WINTER;
public static com.xxxx.SeasonEnum[] values();
public static com.xxxx.SeasonEnum valueOf(java.lang.String);
public static void main(java.lang.String[]);
static {};
}
可以发现其实Enum只是一个语法糖,java编译器会将其编译成一个继承了Enum<E extends Enum<E>>
抽象类的一个类,这个类有所定义的四个静态对象,而对枚举的使用SeasonEnum.SPRING
其实就是使用类的静态字段
public final class com.xxxx.SeasonEnum extends java.lang.Enum<com.xxxx.SeasonEnum>{
public static SeasonEnum[] values(){
return (SeasonEnum[])$VALUES.clone();
}
public static SeasonEnum valueOf(String name){
return (SeasonEnum)Enum.valueOf(enum01/SeasonEnum, name);
}
private SeasonEnum(String s, int i){
super(s, i);
}
public static final SeasonEnum SPRING;
public static final SeasonEnum SUMMER;
public static final SeasonEnum FALL;
public static final SeasonEnum WINTER;
private static final SeasonEnum $VALUES[];
static {
SPRING = new SeasonEnum("春天", "春暖花开");
SUMMER = new SeasonEnum("夏天", "炎炎盛夏");
FALL = new SeasonEnum("秋天", "秋高气爽");
WINTER = new SeasonEnum("冬天", "大雪纷飞");
$VALUES = (new SeasonEnum[] {
SPRING, SUMMER, FALL, WINTER
});
}
}
以上是关于Enum的真正面目的主要内容,如果未能解决你的问题,请参考以下文章