Java 基础之枚举类及常见用法
共计 1844 个字符,预计需要花费 5 分钟才能阅读完成。
Java 枚举类(Enum)是一种特殊的数据类型,用于定义一组常量。
例如 web 请求状态码枚举类如下:
public enum ResultCode {
/**
* 请求成功状态码
*/
SUCCESS(200, "成功"),
/**
* 请求失败状态码
*/
FAIL(1000, "失败");
private int code;
private String msg;
private static final Map<Integer, ResultCode> codeMsgMap = new HashMap<>();
private static final Map<String, ResultCode> msgCodeMap = new HashMap<>();
static {
for (ResultCode resultCode : ResultCode.values()) {
codeMsgMap.put(resultCode.getCode(), resultCode);
msgCodeMap.put(resultCode.getMsg(), resultCode);
}
}
ResultCode(int code, String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public static Map<Integer, ResultCode> getCodeMsgMap() {
return codeMsgMap;
}
public static Map<String, ResultCode> getMsgCodeMap() {
return msgCodeMap;
}
public static ResultCode getMsgByCode(int code){
for (ResultCode resultCode : ResultCode.values()) {
if(resultCode.getCode() == code){
return resultCode;
}
}
return null;
}
}
常见用法,一下列举出了枚举类的常见用法:
public class EmunTest {
/**
* 枚举类基本使用
*/
@Test
public void test1() {
System.out.println(ResultCode.SUCCESS.getMsg() + ": " + ResultCode.SUCCESS.getCode());
}
/**
* 枚举类遍历
*/
@Test
public void test2() {
for (ResultCode resultCode : ResultCode.values()) {
System.out.println("Code: " + resultCode.getCode());
System.out.println("Message: " + resultCode.getMsg());
System.out.println("--------------------------");
}
}
/**
* 测试自己写的 getByCode 方法获取枚举常量
*/
@Test
public void test3() {
int code = 1000;
ResultCode resultCode = ResultCode.getByCode(code);
if (resultCode != null) {
System.out.println(resultCode.getMsg() + ": " + resultCode.getCode());
}
}
/**
* 通过静态代码块,通过 map 获取枚举常量
*/
@Test
public void test4() {
// 通过 code 获取枚举常量
int code = 200;
ResultCode resultCode = ResultCode.getCodeMsgMap().get(code);
if (resultCode != null) {
System.out.println(resultCode.getMsg() + ": " + resultCode.getCode());
}
// 通过 msg 获取枚举常量
String msg = "失败";
ResultCode resultCode2 = ResultCode.getMsgCodeMap().get(msg);
if (resultCode2 != null) {
System.out.println(resultCode2.getMsg() + ": " + resultCode2.getCode());
}
}
}
提醒:本文发布于404天前,文中所关联的信息可能已发生改变,请知悉!
Tips:清朝云网络工作室
阅读剩余
THE END