我经常使用这种技术,但我不确定如何调用它。我称之为关联枚举。对吗?
例子:
public enum Genders {
Male("M"), Female("F"), Transgender("T"), Other("O"), Unknown("U");
private String code;
Genders(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public static Genders get(String code) {
for (Genders gender : values()) {
if (gender.getCode().equalsIgnoreCase(code)) {
return gender;
}
}
return null;
}
}
最佳答案
我有一组用于执行此操作的类,但除了 Encodable
interface Encodable<T>{
T getCode();
}
public class EnumUtils{
public static <U, T extends Enum<T> & Encodable<U>> T getValueOf(
@Nonnull Class<T> enumClass,
@Nullable U code){
for (T e : enumClass.getEnumConstants()){
if (Objects.equal(e.getCode(), code))
return e;
}
throw new IllegalArgumentException("No enum found for " + code);
}
}
关于java - 这个枚举模式叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10987726/