JavaWeb项目中需要定义各种常量时,常用方法有:

本篇主要记录用魔法数字和枚举类的方法。

定义一个常量类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());

 

相关文章:

  • 2021-12-06
  • 2022-12-23
  • 2021-09-20
  • 2022-12-23
  • 2022-02-09
  • 2021-08-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-31
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
相关资源
相似解决方案