关于Constant常量和枚举类Enum的定义和使用

@关于Constant常量和枚举类Enum的定义和使用

自定义常量Constant

final类中定义一个内部接口的方式来定义常量,有如下好处: 1就是归类,使用起来也非常方便。2就是少些很多多余的public static final 的前缀,代码简洁。3就是便于规范取名。

public final class Constant {
	
	public interface UpperCaseNumber {
		String ONE = "壹";
		String TWO = "贰";
		String THREE = "叁";
		String FOUR = "肆";
		String FIVE = "伍";
		String SIX = "陆";
		String SEVEN = "柒";
		String EGHIT = "捌";
		String NINE = "玖";
		String TEN = "拾";
	}

	public interface LowerCaseNumber {
		String ONE = "一";
		String TWO = "二";
		String THREE = "三";
		String FOUR = "四";
		String FIVE = "五";
		String SIX = "六";
		String SEVEN = "七";
		String EGHIT = "八";
		String NINE = "九";
		String TEN = "十";
	}
}

自定义枚举类StatusEnum

这里只讨论枚举类它用在switch循环中在值判断。我们知道,switch-case 中的case XX:,其中的XX不能是变量,那如何巧妙使用枚举类来做条件判断呢?请看如下代码:

public enum StatusEnum {
	
	SUCCESS(0,"成功"),
	FAILURE(1,"失败"),
	UNKNOWN(-1,"未知");

	private int key;
	private String value;
	
	private StatusEnum(int key, String value) {
		this.key = key;
		this.value = value;
	}
	// 这个方法比较有用,主要用于switch循环判断
	public StatusEnum getById(Integer id) {  
        for (StatusEnum statusEnum : values()) {  
            if (statusEnum.getKey() == id) {  
                return statusEnum;  
            }  
        }  
        return null;  
    }  	

	public int getKey() {
		return key;
	}

	public void setKey(int key) {
		this.key = key;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
}

编写main函数

@Slf4j
public class Main {

	    public static void main(String[] args) {
	  		  enumSwitch(-1);
	  		  enumSwitch(0);
	  		  enumSwitch(1);
	    }
		public static void enumSwitch(int statusCode) {
		
			if(Objects.isNull(StatusEnum.getById(statusCode))) {
				log.info(statusCode + " 找不到进入该分支");
				return ;
			}
			switch (StatusEnum.getById(statusCode)) {  
				case SUCCESS:
					log.info(statusCode + " 成功进入该分支");
					break;
				case FAILURE:
					log.info(statusCode + " 失败进入该分支");
					break;
				default:
					log.info(statusCode + " 默认进入该分支");
					break;
			}
		}
}

你可能感兴趣的:(Java)