java - 这个枚举模式叫什么?

标签 java enums

我经常使用这种技术,但我不确定如何调用它。我称之为关联枚举。对吗?

例子:

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/

相关文章:

java - 使用可视化 GUI 编辑器对学习 GUI 设计有害吗?

java - 尽管元素在网页中可见,但无法找到该元素

java - 检查用户登录情况

swift - 类型名称后预期的成员名称或构造函数调用

c# - 如何在 C# 中声明枚举的二维数组?

java - 使用 java 9 和 maven 的 spring boot 应用程序编译失败

java - 实际命令行运行时引用变量返回错误 "No longer attached to the DOM"

angular - Typescript:如何使用枚举来强制数组仅包含该枚举中的特定值?

c# - 通过泛型类中嵌套枚举的反射获取枚举值

c# - 使用类作为事件标识符