Menu Home

Java Enum

Java的Enum搞的越来越强大,用着也越来越别扭。看看下面的代码:

public class TestJavaEnum {

    static enum WorkDay {
        Mon("Monday"),
        Tue("Tuesday"),
        Wed("Wednesday"),
        Thu("Thursday"),
        Fri("Friday");

        private String mDay;

        private WorkDay(String day) {
            mDay = day;
        }

        @Override
        public String toString() {
            return mDay;
        }
    }

    public static void main(String[] args) {
        WorkDay[] workDays = WorkDay.values();

        System.out.println("------WorkDay------");
        for (int i = 0; i < workDays.length; i++) {
            WorkDay workDay = workDays[i];
            System.out.println(workDay.toString());
        }

        System.out.println("------Ordinal------");

        for (int i = 0; i < workDays.length; i++) {
            WorkDay workDay = workDays[i];
            System.out.println(workDay.toString() + "'s ordinal is "
                    + workDay.ordinal());
        }

        System.out.println("------ValueOf------");

        System.out.println(WorkDay.valueOf("Mon"));

    }
}

Output:

------WorkDay------
Monday
Tuesday
Wednesday
Thursday
Friday
------Ordinal------
Monday's ordinal is 0
Tuesday's ordinal is 1
Wednesday's ordinal is 2
Thursday's ordinal is 3
Friday's ordinal is 4
------ValueOf------
Monday

下面我们反编译看一下,Java究竟对Enum做了啥?

javap -c TestJavaEnum\$WorkDay

从反编译的结果中我们发现了下面的代码:

final class net.lnmcc.TestJavaEnum$WorkDay extends java.lang.Enum{

这说明Java中的Enum实际上是继承了java.lang.Enum的类。
继续往下看反编译的结果有:

public static final net.lnmcc.TestJavaEnum$WorkDay Mon;
public static final net.lnmcc.TestJavaEnum$WorkDay Tue;
public static final net.lnmcc.TestJavaEnum$WorkDay Wed;
public static final net.lnmcc.TestJavaEnum$WorkDay Thu;
public static final net.lnmcc.TestJavaEnum$WorkDay Fri;

我们定义的的每一个Enum值都成了一个WorkDay Class的静态对象。
继续往下看:

   0:	new	#1; //class net/lnmcc/TestJavaEnum$WorkDay
   3:	dup
   4:	ldc	#18; //String Mon
   6:	iconst_0
   7:	ldc	#19; //String Monday
   9:	invokespecial	#21; //Method "<init>":(Ljava/lang/String;ILjava/lang/String;)V
   12:	putstatic	#25; //Field Mon:Lnet/lnmcc/TestJavaEnum$WorkDay;
   15:	new	#1; //class net/lnmcc/TestJavaEnum$WorkDay
   18:	dup

原来Java会调用构造方法来构造我们的Enum对象,参数即为定义Enum时我们在括号中给出的值。
到这里对Java Enum的实现算是清楚了,但是呢,用起来还是别扭,哈哈。

Leave a Reply

Your email address will not be published.