实际开发中,我们通常在数据库中使用数字作为状态的值,但是返给前台要展示的时候要显示具体的内容是什么,这个时候就要使用遍历,再set,这样做代码看起来很笨重。下面做一个简单的方法使用枚举类来快速的返回状态的内容。
时间: 2024-02-03 12:11:16 浏览: 22
好的,我来给您写一段示例代码:
```java
public enum StatusEnum {
SUCCESS(0, "成功"),
FAILURE(1, "失败"),
UNAUTHORIZED(2, "未授权"),
FORBIDDEN(3, "禁止访问");
private Integer code;
private String message;
StatusEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
public static String getMessageByCode(Integer code) {
for (StatusEnum status : values()) {
if (status.getCode().equals(code)) {
return status.getMessage();
}
}
return null;
}
}
```
在这个示例中,我们定义了一个枚举类 `StatusEnum`,其中包含了常见的状态值和对应的文字说明。通过 `getMessageByCode` 方法,可以根据状态码直接返回对应的文字说明。这样就可以避免在代码中使用大量的 if-else 或者 switch-case 来进行状态判断和设置,让代码更加简洁易读。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)