JavaWeb項目中需要定義各種常量時,常用方法有:
- 寫到Property配置文件中,用靜態代碼塊優先加載配置文件。參考http://www.cnblogs.com/guxin/p/java-properties-example.html
- 用static final修飾的變量。
- 定義魔法數字。
- 使用枚舉類。
本篇主要記錄用魔法數字和枚舉類的方法。
定義一個常量類Const.java。
package com.mmall.common; /** * Created by Gu on 2018/1/6 0006. * 常量類 */ public class Const { public static final String CURRENT_USER = "currentUser"; public static final String EMAIL = "email"; public static final String USERNAME = "username"; // 不用枚舉也能實現將普通用戶和管理員放到同一組中 public interface Role{ int ROLE_CUSTOMER = 0; // 普通用戶 int ROLE_ADMIN = 1; // 管理員 } // 枚舉類,商品的銷售狀態:在線/下架 public enum ProductStatusEnum{ ON_SALE(1, "在線"); // 通過構造函數定義枚舉值 private String value; private int code; ProductStatusEnum(int code, String value) { this.code = code; this.value = value; } public String getValue() { return value; } public int getCode() { return code; } } }
使用常量。
System.out.println(Const.CURRENT_USER);
System.out.println(Const.Role.ROLE_ADMIN);
System.out.println(Const.ProductStatusEnum.ON_SALE.getCode());