Enum本质是静态成员变量.
public enum Enum {
A(1,2),B(1,2);
int a;
int b;
Enum(int i, int i1) {
this.a = i;
this.b = i1;
}
}
以上代码经过javap反编译,得到结果为:
public final class Enum extends java.lang.Enum<Enum> {
public static final Enum A;
public static final Enum B;
int a;
int b;
public static Enum[] values();
Code:
0: getstatic #1 // Field $VALUES:[LEnum;
3: invokevirtual #2 // Method "[LEnum;".clone:()Ljava/lang/Object;
6: checkcast #3 // class "[LEnum;"
9: areturn
public static Enum valueOf(java.lang.String);
Code:
0: ldc #4 // class Enum
2: aload_0
3: invokestatic #5 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast #4 // class Enum
9: areturn
static {};
Code:
0: new #4 // class Enum
3: dup
4: ldc #9 // String A
6: iconst_0
7: iconst_1
8: iconst_2
9: invokespecial #10 // Method "<init>":(Ljava/lang/String;III)V
12: putstatic #11 // Field A:LEnum;
15: new #4 // class Enum
18: dup
19: ldc #12 // String B
21: iconst_1
22: iconst_1
23: iconst_2
24: invokespecial #10 // Method "<init>":(Ljava/lang/String;III)V
27: putstatic #13 // Field B:LEnum;
30: iconst_2
31: anewarray #4 // class Enum
34: dup
35: iconst_0
36: getstatic #11 // Field A:LEnum;
39: aastore
40: dup
41: iconst_1
42: getstatic #13 // Field B:LEnum;
45: aastore
46: putstatic #1 // Field $VALUES:[LEnum;
49: return
}
public static final Enum A;
public static final Enum B;
从以上地方可以看出,是jdk帮助我们创建了两个静态成员变量.