In our code there are 10's of enum classes with same template code pasted each and every time when ever a new enum class needs to be created.
Need a way to generic way to avoid duplication of this code.
Below are couple of same enums classes
Class-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");
}
}
Class-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");
}
}
Need a generic a solution which handles all the methods in class.