zoukankan      html  css  js  c++  java
  • 【Java】定义魔法数字,以及枚举类的构造方法的使用

    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());
  • 相关阅读:
    C#微信开发
    3-4:字符串方法
    2-4-1 元组
    2-3-3 列表方法
    2-2-3:序列(字符串)乘法(p32)
    3-3字符串格式化(p47)
    2-2:分片
    2-1:Print date(p28)
    old.2.三次登录机会
    old.2.sum(1-2+3-4+...+99)
  • 原文地址:https://www.cnblogs.com/guxin/p/java-const-example.html
Copyright © 2011-2022 走看看