java5增加了enum,其实对enum的处理很简单,编译器增加了一些功能而以。
看代码:
public enum Season{
Spring,Summer,Autumn,Winter
}
javap -c Season
就可以看出来具体的处理了,不过直接反编译更容易理解,使用jad处理的结果。
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Season.java
public final class Season extends Enum
{
public static final Season[] values()
{
return (Season[])$VALUES.clone();
}
public static Season valueOf(String s)
{
return (Season)Enum.valueOf(Season, s);
}
private Season(String s, int i)
{
super(s, i);
}
public static final Season Spring;
public static final Season Summer;
public static final Season Autumn;
public static final Season Winter;
private static final Season $VALUES[];
static
{
Spring = new Season("Spring", 0);
Summer = new Season("Summer", 1);
Autumn = new Season("Autumn", 2);
Winter = new Season("Winter", 3);
$VALUES = (new Season[] {
Spring, Summer, Autumn, Winter
});
}
}
一个从java.lang.Enum<E>继承下来的final类,没有什么特殊的地方。使用的时候
Season season = Season.Spring;
不过就是直接访问了Season类中定义的静态常量Spring而已。
其实从java 5开始加入的一些新的语法特性,都是编译器增加了处理,而对于jvm而言,基本不需要什么变化。