Enum使用

Enum使用

统一枚举的操作,枚举类实现该接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Arrays;
import java.util.Optional;

/**
* 枚举操作接口
* @author: yecao
*/
public interface EnumOperate {

Integer getCode();

String getDescription();

/**
* 根据枚举类型和code获取对应的枚举
* @param c 枚举类型
* @param code 枚举code
* @param <T> T extends EnumOperate
* @return 枚举值
*/
static <T extends EnumOperate> T valueOfEnum(Class<T> c, int code) {
EnumOperate[] enums = c.getEnumConstants();
Optional<EnumOperate> optional = Arrays.stream(enums)
.filter(baseCode -> baseCode.getCode().equals(code)).findAny();
if (optional.isPresent()) {
return (T) optional.get();
}
throw new IllegalArgumentException(String.format("[%s]没有对应枚举值: [%s]", c.getName(), code));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
*open api状态码维护
* @author: yecao
*/
public enum OpenApiStatueCode implements EnumOperate {

FORBIDDEN(403, "没有该open api 接口的请求权限"),

COUNTRY_EXPIRED(401, "对该open api接口请求的权限已到期"),

REQUEST_TIMEOUT(408, "X-Timestamp超时");

private final Integer code;

private final String description;

OpenApiStatueCode(Integer code, String description) {
this.code = code;
this.description = description;
}

@Override
public Integer getCode() {
return this.code;
}

@Override
public String getDescription() {
return this.description;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!