java中的常量定义,final 的问题
3452 点击·0 回帖
![]() | ![]() | |
![]() | 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; } | |
![]() | ![]() |