本文介绍了我可以根据其字段的值获取枚举吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想根据字段值获取特定的枚举.枚举:public enum CrimeCategory {ASBO(反社会行为"),BURG(入室盗窃"),CRIMDAM(刑事损害和纵火"),药物(药物"),OTTHHEFT(其他盗窃"),PUPDISOR(公共骚乱和武器"),抢劫(抢劫"),SHOPLIF(入店行窃"),车辆(车辆犯罪"),暴力(暴力犯罪"),其他(其他犯罪");私有字符串类别;私人犯罪类别(字符串类别){this.category = 类别;}公共字符串 returnString() {退货类别;}}获取新的枚举:aStringRecivedFromJson = "反社会行为"犯罪类别犯罪类别枚举;CrimeCategoryEnum = CrimeCategory.valueOf(aStringRecivedFromJson);我一直在尝试为上述方法找到一种方法,带回一个枚举,以便它可以与其他 Crime 信息一起存储在 HashMap 中.>预期结果:ASBO 解决方案 作为参考,这里是一个带有 HashMap 的替代解决方案:enum CrimeCategory {ASBO("反社会行为"),BURG("入室盗窃"),CRIMDAM(刑事损害和纵火"),药物(药物"),OTTHHEFT("其他盗窃"),PUPDISOR(公共骚乱和武器"),抢劫(抢劫"),SHOPLIF("入店行窃"),车辆(车辆犯罪"),暴力(暴力犯罪"),其他(其他犯罪");private static final Mapmap = new HashMap(values().length, 1);静止的 {for (CrimeCategory c : values()) map.put(c.category, c);}私有最终字符串类别;私人犯罪类别(字符串类别){this.category = 类别;}公共静态犯罪类别(字符串名称){犯罪类别结果 = map.get(name);如果(结果 == 空){throw new IllegalArgumentException("类别名称无效:" + name);}返回结果;}}I want to get a specific enum based on its field value.Enum:public enum CrimeCategory { ASBO ("Anti Social Behaviour"), BURG ("Burglary"), CRIMDAM ("Criminal Damage And Arson"), DRUGS ("Drugs"), OTHTHEFT ("Other Theft"), PUPDISOR ("Public Disorder And Weapons"), ROBBERY ("Robbery"), SHOPLIF ("Shoplifting"), VEHICLE ("Vehicle Crime"), VIOLENT ("Violent Crime"), OTHER ("Other Crime"); private String category; private CrimeCategory (String category) { this.category = category; } public String returnString() { return category; }}Getting a new Enum:aStringRecivedFromJson = "Anti Social Behaviour"CrimeCategory crimeCategoryEnum;crimeCategoryEnum = CrimeCategory.valueOf(aStringRecivedFromJson);I have been trying to work out a way for the above bring back a an enum so it can be passed stored in a HashMap with other Crime information.Expected Result: ASBO 解决方案 For reference, here is an alternative solution with a HashMap:enum CrimeCategory { ASBO("Anti Social Behaviour"), BURG("Burglary"), CRIMDAM("Criminal Damage And Arson"), DRUGS("Drugs"), OTHTHEFT("Other Theft"), PUPDISOR("Public Disorder And Weapons"), ROBBERY("Robbery"), SHOPLIF("Shoplifting"), VEHICLE("Vehicle Crime"), VIOLENT("Violent Crime"), OTHER("Other Crime"); private static final Map<String, CrimeCategory> map = new HashMap<>(values().length, 1); static { for (CrimeCategory c : values()) map.put(c.category, c); } private final String category; private CrimeCategory(String category) { this.category = category; } public static CrimeCategory of(String name) { CrimeCategory result = map.get(name); if (result == null) { throw new IllegalArgumentException("Invalid category name: " + name); } return result; }} 这篇关于我可以根据其字段的值获取枚举吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-18 18:45