Java 中我們常常需要定義一些常量ID,ID值為連續不重復值
方法1:, 方便的定義,方便增減ID 非常方便, 程序保證不會有重復的ID
public static class HandleMessage{
// 常量這樣定義, switch 語句過不去
final static int HM_USER = 0x100;
private static int _id = 1;
public final static int HM_INIT_ERROR = HM_USER + ++_id;
public final static int HM_INIT_COMPLETE = HM_USER + ++_id;
}
方法2, 定義較死板,增減ID 需要注意,是否有重復的ID,由定義者來保證,多人開發時這個很難保證,
public static class HandleMessage{
final static int HM_USER = 0x100;
public final static int HM_INIT_ERROR = HM_USER + 1;
public final static int HM_INIT_COMPLETE = HM_USER + 2;
}
代碼中,
switch(id){
case HandleMessage.HM_INIT_ERROR:
//方法1 無法編譯提示錯誤, case expressions must be constant expressions
//方法2 正常
break;
}
新聞熱點
疑難解答