【发布时间】:2017-10-01 20:03:35
【问题描述】:
在我们的代码中,每次需要创建新的枚举类时,都会粘贴 10 个具有相同模板代码的枚举类。
需要一种通用方法来避免重复此代码。
下面是几个相同的枚举类
1 类
public enum AccountStatus {
ACTIVE("ACTIVE", 1),
INACTIVE("INACTIVE", 2);
private final int value;
private final String key;
AccountStatus(String key, int value) {
this.value = value;
this.key = key;
}
public int getValue() {
return this.value;
}
public String getKey() {
return this.key;
}
@Override
public String toString() {
return String.valueOf(this.value);
}
@JsonCreator
public static AccountStatus create(String key) {
if (key == null) {
throw new IllegalArgumentException();
}
for (AccountStatus v : values()) {
if (v.getKey().equalsIgnoreCase(key)) {
return v;
}
}
throw new IllegalArgumentException();
}
public static AccountStatus fromValue(Integer value) {
for (AccountStatus type : AccountStatus.values()) {
if (value == type.getValue()) {
return type;
}
}
throw new IllegalArgumentException("Invalid enum type supplied");
}
public static AccountStatus fromValue(String key) {
for (AccountStatus type : AccountStatus.values()) {
if (type.getKey().equalsIgnoreCase(key)) {
return type;
}
}
throw new IllegalArgumentException("Invalid enum type supplied");
}
}
2 级
public enum Gender {
MALE("MALE", 1),
FEMALE("FEMALE", 2);
private final int value;
private final String key;
Gender(String key, int value) {
this.value = value;
this.key = key;
}
public int getValue() {
return this.value;
}
public String getKey() {
return this.key;
}
@Override
public String toString() {
return String.valueOf(this.value);
}
@JsonCreator
public static Gender create(String key) {
if (key == null) {
throw new IllegalArgumentException();
}
for (Gender v : values()) {
if (v.getKey().equalsIgnoreCase(key)) {
return v;
}
}
throw new IllegalArgumentException();
}
public static Gender fromValue(Integer value) {
for (Gender type : Gender.values()) {
if (value == type.getValue()) {
return type;
}
}
throw new IllegalArgumentException("Invalid enum type supplied");
}
public static Gender fromValue(String gender) {
for (Gender type : Gender.values()) {
if (type.getKey().equalsIgnoreCase(gender)) {
return type;
}
}
throw new IllegalArgumentException("Invalid enum type supplied");
}
}
需要一个通用的解决方案来处理类中的所有方法。
【问题讨论】:
-
我的意思是键只是
name()而值是ordinal() + 1所以嗯 -
虽然,不知道是否推荐。