在我们的代码中,有 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");
}
}
需要一个通用的解决方案来处理类中的所有方法。
最佳答案
我可以看到两个选项,并且都涉及接口(interface)。但无论哪种情况,您仍然需要为枚举创建构造函数并声明字段。
- 在枚举上为
getValue
和getKey
方法实现一个接口(interface),然后移动create
和fromValue
将枚举类作为参数的实用程序类的方法。例如
EnumUtility.create(AccountStatus.class, "ACTIVE");
- 使用 JDK8 接口(interface)声明将继承到枚举中的默认方法实现。
关于使用反射的 Java 通用枚举类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43769374/