java的枚舉類型聲明非常簡單净当,這里我們聲明一個只有兩個枚舉值的TypeB
public enum TypeB {
A,B;
}
隨后編譯器生成TypeB.class文件,我們來研究下里面藏了什么
首先是靜態(tài)變量和靜態(tài)代碼塊:
{
public static final testAnything.TypeB A;
public static final testAnything.TypeB B;
//聲明兩個TypeB的實例瓣戚,和我們聲明的枚舉值同名
static {};
flags: ACC_STATIC
Code:
stack=4, locals=0, args_size=0
0: new #1 // class testAnything/TypeB
3: dup
4: ldc #13 // String A
6: iconst_0
7: invokespecial #14 // Method "<init>":(Ljava/lang/String;I)V
10: putstatic #18 // Field A:LtestAnything/TypeB;
//調用Enum(String,int)方法球碉,生成TypeB.A
13: new #1 // class testAnything/TypeB
16: dup
17: ldc #20 // String B
19: iconst_1
20: invokespecial #14 // Method "<init>":(Ljava/lang/String;I)V
23: putstatic #21 // Field B:LtestAnything/TypeB;
//調用Enum(String,int)方法撞蜂,生成TypeA.B
26: iconst_2
27: anewarray #1 // class testAnything/TypeB
//生成一個長度為2的TypeB[]
30: dup
31: iconst_0
32: getstatic #18 // Field A:LtestAnything/TypeB;
35: aastore
36: dup
37: iconst_1
38: getstatic #21 // Field B:LtestAnything/TypeB;
41: aastore
42: putstatic #23 // Field ENUM$VALUES:[LtestAnything/TypeB;
//將A,B的值放入TypeB[]盲镶,并賦值給私有靜態(tài)變量ENUM$VALUE
45: return
上面這部分字節(jié)碼指令主要做了兩件事:
- 為兩個公共靜態(tài)變量A和B賦值
- 將A,B的值存入私有靜態(tài)變量ENUM$VALUES中
這里的ENUM$VALUES變量名是可變的侥袜,如果在enum類中聲明了同名的變量,編譯器選用其他變量名溉贿。
下面是values()靜態(tài)方法枫吧,它返回枚舉類型的所有枚舉值:
public static testAnything.TypeB[] values();
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=5, locals=3, args_size=0
0: getstatic #25 // Field ENUM$VALUES:[LtestAnything/TypeB;
3: dup
4: astore_0
5: iconst_0
6: aload_0
7: arraylength
8: dup
9: istore_1
10: anewarray #1 // class testAnything/TypeB
13: dup
14: astore_2
15: iconst_0
16: iload_1
17: invokestatic #33 // Method java/lang/System.arraycopy:(Ljava/lang/Object;ILjava/lang/Object;II)V
20: aload_2
21: areturn
這個方法做的事只有一件,拷貝ENUM$VALUE并返回宇色。具體流程大家有興趣可以自己畫下運行棧和變量表九杂。
接下來是繼承自Enum類的valueOf方法:
public static testAnything.TypeB valueOf(java.lang.String);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: ldc #1 // class testAnything/TypeB
2: aload_0
3: invokestatic #41 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast #1 // class testAnything/TypeB
9: areturn
}
這個方法與它重寫的方法唯一的區(qū)別就是把返回值類型由Object變?yōu)門ypeB。
這樣宣蠕,我們就可以模擬寫出TypeB.java了:
public class TypeB extends Enum{
//上面的繼承會報錯例隆,不能顯式的繼承Enum
public static TypeB A;
public static TypeB B;
private static TypeB[] ENUM$VALUE ;
static{
A = new Enum(A,0);
B = new Enum(B,1);
//上面的調用無法編譯通過,Enum的修飾符是protected
TypeB[] newarr = new TypeB[2];
newarr[0] = A;
newarr[1] = B;
ENUM$VALUE = newarr;
}
public static TypeB[] values(){
int length = ENUM$VALUE.length;
TypeB[] newArr = new TypeB[length];
System.arraycopy(ENUM$VALUE, 0, newArr, 0, length);
return newArr;
}
public static TypeB valueOf(String name){
return (TypeB)Enum.valueOf(TypeB.class, name);
}
}