1. 程式人生 > >JAVA的列舉enum型別 && JAVA的JSON示例

JAVA的列舉enum型別 && JAVA的JSON示例

(1) 關於Java Enum:學過C/C++等語言的人,應該都對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為列舉型別提供了一些內建的方法,同時列舉常量還可以有自己的方法,可以很方便的遍歷列舉物件。

(3)例項

enum類檔案WeekDay.java:

public enum WeekDay {
	Mon("Monday"),	//兩個應該都是String型別
	Tue("Tuesday"),
	Wed("Wednesday"),
	Thu("Thursday"),
	Fri("Friday"),
	Sat("Saturday"),
	Sun("Sunday");
	
	private final String day;
	
	private WeekDay(String day) {	//enum類的建構函式
	     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;	//輸出的其實是enum的值,而不是成員對應的string值
	     default:System.out.println("wrong number!");
	     }
	}
	
	public String getDay() {
	     return day;
	}
}

測試檔案 WeekDayTest.java:

public class WeekDayTest {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for (WeekDay day : WeekDay.values()) {   //迴圈計數
	              System.out.println(day + "====>" + day.getDay());   //enum值  enum對應的string值
		}
		WeekDay.printDay(5);
	}
}

     執行結果是:

Mon====>Monday
Tue====>Tuesday
Wed====>Wednesday
Thu====>Thursday
Fri====>Friday
Sat====>Saturday
Sun====>Sunday
Fri
(4)java enum本質

        Java Enum型別的語法結構儘管和java類的語法不一樣,但是經過編譯器編譯之後產生的是一個class檔案。該class檔案經過反編譯可以看到實際上是生成了一個類,該類繼承了java.lang.Enum。

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);
}

所以實際上Enum型別就是以Java類來實現的,沒有什麼新的特點,只不過java編譯器幫我們做了語法的解析和編譯。

(5)java的ordinal函式

       Enum類提供了一個ordinal()方法,用來返回列舉物件的序數。

private static enum gene_actions{
  ACTION0,
  ACTION1,
  ACTION2,
  ACTION3,

 }
 public final static int INVALID_ACTION = gene_actions.ACTION0.ordinal();
 public final static int SMART_HANDFREE_ACTION = gene_actions.ACTION1.ordinal();
 public final static int ANTI_EAVESDROP_ACTION = gene_actions.ACTION2.ordinal();
 public final static int DIRECT_CALL_ACTION = gene_actions.ACTION3.ordinal();

得到序數值就是0 1 2 3
================================================================================================================

       在ECLIPSE中的某個工程使用json,需要匯入額外的json包,比如json-20090211.jar。從網上下到這個庫之後,放到工程目錄下,在project匯入的方法是:點選工程右鍵-》屬性-》Java build path-》libraries,再點選右邊的add external JARs,選中剛才放置的Jar包就可以了。

       比如如下的工程,從網站地理位置資料中返回特定資料

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;
/**
 * java根據url獲取json物件
 * @author openks
 * @since 2013-7-16
 * 需要新增java-json.jar才能執行
 */
public class TestJava {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
     // System.out.println("同時 從這裡也能看出 即便return了,仍然會執行finally的!");
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
   //這裡呼叫百度的ip定位api服務 詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
    JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=202.198.16.3");
    System.out.println(json.toString());
    System.out.println();
    System.out.println(((JSONObject) json.get("content")).get("address"));
  }
}

執行結果是

{"content":{"point":{"y":"5419815.34","x":"13950002.65"},"address":"吉林省長春市","address_detail":{"street":"","province":"吉林省","city_code":53,"street_number":"","district":"","city":"長春市"}},"status":0,"address":"CN|吉林|長春|None|CERNET|0|0"}

吉林省長春市