假设我有一个枚举

public enum Blah {
    A, B, C, D
}

我想找到一个字符串的枚举值,例如“a”,它将是Blah.a。如何做到这一点?

Enum.valueOf()是我需要的方法吗?如果是,我将如何使用它?


当前回答

一种O(1)方法,灵感来自Thrift生成的代码,该代码使用哈希图。

public enum USER {
        STUDENT("jon",0),TEACHER("tom",1);

        private static final Map<String, Integer> map = new HashMap<>();

        static {
                for (USER user : EnumSet.allOf(USER.class)) {
                        map.put(user.getTypeName(), user.getIndex());
                }
        }

        public static int findIndexByTypeName(String typeName) {
                return map.get(typeName);
        }

        private USER(String typeName,int index){
                this.typeName = typeName;
                this.index = index;
        }
        private String typeName;
        private int index;
        public String getTypeName() {
                return typeName;
        }
        public void setTypeName(String typeName) {
                this.typeName = typeName;
        }
        public int getIndex() {
                return index;
        }
        public void setIndex(int index) {
                this.index = index;
        }

}

其他回答

获取enum名称的最快方法是在应用程序启动时创建enum文本和值的映射,并调用函数Blah.getEnumName()获取名称:

public enum Blah {
    A("text1"),
    B("text2"),
    C("text3"),
    D("text4");

    private String text;
    private HashMap<String, String> map;
    Blah(String text) {
    this.text = text;
    }

    public String getText() {
      return this.text;
    }

    static{
      createMapOfTextAndName();
    }

    public static void createMapOfTextAndName() {
        map = new HashMap<String, String>();
        for (Blah b : Blah.values()) {
             map.put(b.getText(),b.name());
        }
    }
    public static String getEnumName(String text) {
        return map.get(text.toLowerCase());
    }
}

最好使用Blah.valueOf(字符串),但也可以使用Enum.valueOf(Blah.class,字符串)。

下面是我使用的一个漂亮的实用程序:

/**
 * A common method for all enums since they can't have another base class
 * @param <T> Enum type
 * @param c enum type. All enums must be all caps.
 * @param string case insensitive
 * @return corresponding enum, or null
 */
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
    if( c != null && string != null ) {
        try {
            return Enum.valueOf(c, string.trim().toUpperCase());
        } catch(IllegalArgumentException ex) {
        }
    }
    return null;
}

然后在我的enum类中,我通常使用这个来保存一些类型:

public static MyEnum fromString(String name) {
    return getEnumFromString(MyEnum.class, name);
}

如果枚举不是全部大写,只需更改Enum.valueOf行。

太糟糕了,因为t被删除,我不能对Enum.valueOf使用t.class。

枚举非常有用。我一直在使用Enum为不同语言的某些字段添加描述,如以下示例:

public enum Status {

    ACT(new String[] { "Accepted", "مقبول" }),
    REJ(new String[] { "Rejected", "مرفوض" }),
    PND(new String[] { "Pending", "في الانتظار" }),
    ERR(new String[] { "Error", "خطأ" }),
    SNT(new String[] { "Sent", "أرسلت" });

    private String[] status;

    public String getDescription(String lang) {
        return lang.equals("en") ? status[0] : status[1];
    }

    Status(String[] status) {
        this.status = status;
    }
}

然后,您可以根据传递给getDescription(Stringlang)方法的语言代码动态检索描述,例如:

String statusDescription = Status.valueOf("ACT").getDescription("en");
public enum DivisionType {
DEFAULT(0){
    @Override
    public void sort(List<SigInUserDto> SigInUserDtos) {
        SigInUserDtos.sort(new SigInUserCoinsQueueComparator());
    }
},
ASSIGNPOINTS(1) {
    @Override
    public void sort(List<SigInUserDto> SigInUserDtos) {
        SigInUserDtos.sort(new SigInUserPointsComparator());
    }
},
ASSIGNEVENORDER(2) {
    @Override
    public void sort(List<SigInUserDto> SigInUserDtos) {
        SigInUserDtos.sort(new SigInUserOrderCountComparator());
    }
};

public final Integer label;

DivisionType(Integer label) {
    this.label = label;
}

public static DivisionType getTypeById(Integer id) {
    for (DivisionType value : DivisionType.values()) {
        if (value.label == id) {
            return value;
        }
    }
    return DEFAULT;
}

public abstract void sort(List<SigInUserDto> SigInUserDtos);
}

使用枚举:DivisionType.getTypeById(object.getBalancingTypesId().intValue()).sort(sigInUserDtoList);

在这里,sort()函数在每个枚举匹配下实现(重载)。因此,基于对象“object.getBalancingTypesId().intValue()”匹配值,调用并排序特定的枚举匹配。