定义枚举数字及枚举类的构造方法的使用
JavaWeb项目中需要定义各种常量时,常用方法有:
-
用static final修饰的变量。
-
定义魔法数字。
-
使用枚举类。
-
写到Property配置文件中,用静态代码块优先加载配置文件。
本篇主要记录用魔法数字和枚举类的方法。
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());