How to get an enum value from a string value in Java?

前端 未结 27 2262
旧巷少年郎
旧巷少年郎 2020-11-21 10:53

Say I have an enum which is just

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

and I would like to find the enum value of a string, for example

27条回答
  •  面向向阳花
    2020-11-21 11:44

    Solution using Guava libraries. Method getPlanet () is case insensitive, so getPlanet ("MerCUrY") will return Planet.MERCURY.

    package com.universe.solarsystem.planets;
    import org.apache.commons.lang3.StringUtils;
    import com.google.common.base.Enums;
    import com.google.common.base.Optional;
    
    //Pluto and Eris are dwarf planets, who cares!
    public enum Planet {
       MERCURY,
       VENUS,
       EARTH,
       MARS,
       JUPITER,
       SATURN,
       URANUS,
       NEPTUNE;
    
       public static Planet getPlanet(String name) {
          String val = StringUtils.trimToEmpty(name).toUpperCase();
          Optional  possible = Enums.getIfPresent(Planet.class, val);
          if (!possible.isPresent()) {
             throw new IllegalArgumentException(val + "? There is no such planet!");
          }
          return possible.get();
       }
    }
    

提交回复
热议问题