Java中的Enum的使用與分析

轉載地址:http://www.cnblogs.com/frankliiu-java/archive/2010/12/07/1898721.html


示例:

public enum EnumTest {
     FRANK("The given name of me"),
     LIU("The family name of me");
     private String context;
     private String getContext(){
      return this.context;
     }
     private EnumTest(String context){
      this.context = context;
     }
     public static void main(String[] args){
      for(EnumTest name :EnumTest.values()){
      System.out.println(name+" : "+name.getContext());
      }
      System.out.println(EnumTest.FRANK.getDeclaringClass());
     }

 Java中枚舉實現的分析:

示例: 

  1. public enum Color{  
  2.     RED,BLUE,BLACK,YELLOW,GREEN  
  3. }  

顯然,enum很像特殊的class,實際上enum聲明定義的類型就是一個類。 而這些類都是類庫中Enum類的子類(java.lang.Enum<E>)。它們繼承了這個Enum中的許多有用的方法。我們對代碼編譯之後發現,編譯器將enum類型單獨編譯成了一個字節碼文件:Color.class。

Color字節碼代碼 
  1. final enum hr.test.Color {  
  2.     
  3.  // 所有的枚舉值都是類靜態常量  
  4.  public static final enum hr.test.Color RED;  
  5.  public static final enum hr.test.Color BLUE;  
  6.  public static final enum hr.test.Color BLACK;  
  7.  public static final enum hr.test.Color YELLOW;  
  8.  public static final enum hr.test.Color GREEN;  
  9.    
  10. private static final synthetic hr.test.Color[] ENUM$VALUES;  
  11.     
  12.   // 初始化過程,對枚舉類的所有枚舉值對象進行第一次初始化  
  13.  static {  
  14.        0  new hr.test.Color [1]   
  15.       3  dup  
  16.       4  ldc <String "RED"> [16] //把枚舉值字符串"RED"壓入操作數棧  
  17.       6  iconst_0  // 把整型值0壓入操作數棧  
  18.       7  invokespecial hr.test.Color(java.lang.String, int) [17] //調用Color類的私有構造器創建Color對象RED  
  19.      10  putstatic hr.test.Color.RED : hr.test.Color [21]  //將枚舉對象賦給Color的靜態常量RED。  
  20.       .........  枚舉對象BLUE等與上同  
  21.     102  return  
  22. };  
  23.     
  24.   // 私有構造器,外部不可能動態創建一個枚舉類對象(也就是不可能動態創建一個枚舉值)。  
  25.  private Color(java.lang.String arg0, int arg1){  
  26.      // 調用父類Enum的受保護構造器創建一個枚舉對象  
  27.      3  invokespecial java.lang.Enum(java.lang.String, int) [38]  
  28. };  
  29.    
  30.  public static hr.test.Color[] values();  
  31.     
  32.    // 實現Enum類的抽象方法    
  33.   public static hr.test.Color valueOf(java.lang.String arg0);  
  34. }  
 

下面我們就詳細介紹enum定義的枚舉類的特徵及其用法。(後面均用Color舉例)

1、Color枚舉類就是class,而且是一個不可以被繼承的final類。其枚舉值(RED,BLUE...)都是Color類型的類靜態常量, 我們可以通過下面的方式來得到Color枚舉類的一個實例:
                                                         Color c=Color.RED; 
注意:這些枚舉值都是public static final的,也就是我們經常所定義的常量方式,因此枚舉類中的枚舉值最好全部大寫。 

2、即然枚舉類是class,當然在枚舉類型中有構造器,方法和數據域。但是,枚舉類的構造器有很大的不同: 
      (1) 構造器只是在構造枚舉值的時候被調用。

Java代碼 
  1. enum Color{  
  2.                 RED(255,0,0),BLUE(0,0,255),BLACK(0,0,0),YELLOW(255,255,0),GREEN(0,255,0);  
  3.                 //構造枚舉值,比如RED(255,0,0)  
  4.                 private Color(int rv,int gv,int bv){  
  5.                  this.redValue=rv;  
  6.                  this.greenValue=gv;  
  7.                  this.blueValue=bv;  
  8.                 }  
  9.   
  10.                 public String toString(){  //覆蓋了父類Enum的toString()  
  11.                 return super.toString()+"("+redValue+","+greenValue+","+blueValue+")";  
  12.                 }  
  13.      
  14.                 private int redValue;  //自定義數據域,private爲了封裝。  
  15.                 private int greenValue;  
  16.                 private int blueValue;  
  17.  }  

      (2) 構造器只能私有private,絕對不允許有public構造器。 這樣可以保證外部代碼無法新構造枚舉類的實例。這也是完全符合情理的,因爲我們知道枚舉值是public static final的常量而已。 但枚舉類的方法和數據域可以允許外部訪問。

Java代碼 
  1. public static void main(String args[])  
  2. {  
  3.         // Color colors=new Color(100,200,300);  //wrong  
  4.            Color color=Color.RED;  
  5.            System.out.println(color);  // 調用了toString()方法  
  6. }     
 

3、所有枚舉類都繼承了Enum的方法,下面我們詳細介紹這些方法。 
       (1)  ordinal()方法: 返回枚舉值在枚舉類種的順序。這個順序根據枚舉值聲明的順序而定。
                 Color.RED.ordinal();  //返回結果:0
                 Color.BLUE.ordinal();  //返回結果:1
       (2)  compareTo()方法: Enum實現了java.lang.Comparable接口,因此可以比較象與指定對象的順序。Enum中的compareTo返回的是兩個枚舉值的順序之差。當然,前提是兩個枚舉值必須屬於同一個枚舉類,否則會拋出ClassCastException()異常。(具體可見源代碼)
                 Color.RED.compareTo(Color.BLUE);  //返回結果 -1
       (3)  values()方法: 靜態方法,返回一個包含全部枚舉值的數組。
                 Color[] colors=Color.values();
                 for(Color c:colors){
                        System.out.print(c+","); 
                 }//返回結果:RED,BLUE,BLACK YELLOW,GREEN,
       (4)  toString()方法: 返回枚舉常量的名稱。
                 Color c=Color.RED;
                 System.out.println(c);//返回結果: RED
       (5)  valueOf()方法: 這個方法和toString方法是相對應的,返回帶指定名稱的指定枚舉類型的枚舉常量。
                 Color.valueOf("BLUE");   //返回結果: Color.BLUE
       (6)  equals()方法: 比較兩個枚舉類對象的引用。

Java代碼 
  1. //JDK源代碼:      
  2. public final boolean equals(Object other) {  
  3.         return this==other;  
  4. }               


4、枚舉類可以在switch語句中使用。

Java代碼 
  1. Color color=Color.RED;  
  2. switch(color){  
  3.         case RED: System.out.println("it's red");break;  
  4.         case BLUE: System.out.println("it's blue");break;  
  5.         case BLACK: System.out.println("it's blue");break;  
  6. }  

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章