java – 我可以根据其字段的值获取枚举吗?

前端之家收集整理的这篇文章主要介绍了java – 我可以根据其字段的值获取枚举吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想根据其字段值获取一个特定的枚举.

枚举:

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; 
    }
}

获得新的枚举:

aStringRecivedFromJson = "Anti Social BehavIoUr"
CrimeCategory crimeCategoryEnum;
crimeCategoryEnum = CrimeCategory.valueOf(aStringRecivedFromJson);

我一直在试图找出一个方法,以便上面提供一个枚举,以便它可以通过与其他犯罪信息一起散布在Hashmap中.
预期成果:ASBO

解决方法

作为参考,这里有一个替代解决方案与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;
  }
}
原文链接:https://www.f2er.com/java/124858.html

猜你在找的Java相关文章