Java中的Enum用法介绍

1. 关于Java Enum:

JDK1.5之前没有Enum这个类型,那时候一般用接口常量来替代。有了JavaEnum之后,可以更贴近的表示这种常量。

2. 如何使用Java Enum

简单的用法:JavaEnum简单的用法一般用于代表一组常用常量,可用来代表一类相同类型的常量值。如:

性别:

public enum SexEnum {

  male, female;

}

颜色:

public enum Color {

  RED, BLUE,GREEN,BLACK;

}



枚举对象里面的值都必须是唯一的。

可以通过Enum类型名直接引用该常量,如SexEnum.male,Color.RED.

复杂用法:Java为枚举类型提供了一些内置的方法,同事枚举常量还可以有自己的方法。可以很方便的遍历枚举对象,看个下面的例子:



1. 代码一 WeekDay.java:





public enum WeekDay {

Mon("Monday"), Tue("Tuesday"), Wed("Wednesday"), Thu("Thursday"), Fri(

        "Friday"), Sat("Saturday"), Sun("Sunday");





private final String day;



private WeekDay(String day) {

     this.day = day;

}





public static void printDay(int i){

     switch(i){

     case 1: System.out.println(WeekDay.Mon); break;

     case 2: System.out.println(WeekDay.Tue);break;

     case 3: System.out.println(WeekDay.Wed);break;

     case 4: System.out.println(WeekDay.Thu);break;

     case 5: System.out.println(WeekDay.Fri);break;

     case 6: System.out.println(WeekDay.Sat);break;

     case 7: System.out.println(WeekDay.Sun);break;

     default:System.out.println("wrong number!");

     }

}



public String getDay() {

     return day;

}

}



2.  代码二 WeekDayTest.java:





public class WeekDayTest {

  public static void main(String args[]) {

      for (WeekDay day : WeekDay.values()) {

         System.out.println(day + "====>" + day.getDay());

      }

      WeekDay.printDay(5);

  }

}



输出结果为:

          Mon====>Monday

Tue====>Tuesday

Wed====>Wednesday

Thu====>Thursday

Fri====>Friday

Sat====>Saturday

Sun====>Sunday

Fri

3. Java Enum原理

Java Enum类型的语法结构尽管和java类的语法不一样,应该说差别比较大。但是经过编译器编译之后产生的是一个class文件。该class文件经过反编译可以看到实际上是生成了一个类,该类继承了java.lang.Enum<E>.

WeekDay经过反编译(javap WeekDay命令)之后得到的内容如下(去掉了汇编代码):

public final class WeekDay extends java.lang.Enum{

    public static final WeekDay Mon;

    public static final WeekDay Tue;

    public static final WeekDay Wed;

    public static final WeekDay Thu;

    public static final WeekDay Fri;

    public static final WeekDay Sat;

    public static final WeekDay Sun;

    static {};

    public static void printDay(int);

    public java.lang.String getDay();

    public static WeekDay[] values();

    public static WeekDay valueOf(java.lang.String);

}


你可能感兴趣的:(java)