开发者

Quick Enum Question

Hey guys, I have a quick question. If given a string Value how can i get the corresponding int value in my enum class?

Ex:

Given a string "Ordinary" I want the value 0 returned. He开发者_JAVA技巧re is what I have:

public enum MembershipTypes 
{
    ORDINARY(0,"Ordinary"),
    WORKING(1,"Working"),
    CORE(2,"Core"),
    COORDINATOR(3,"Coordinator");

    private int intVal;
    private String strVal;

    /**
     * 
     * @param intValIn
     * @param strValIn
     */
    MembershipTypes(int intValIn, String strValIn)
    {
        intVal = intValIn;
        strVal = strValIn;
    }

    /**
     * 
     * Gets the integer value
     * @return intVal
     */
    public int getIntVal() 
    {
        return intVal;
    }

    /**
     * 
     * Gets the string value
     * @return strVal
     */
    public String getStrVal() 
    {
        return strVal;
    }
}


Here's the simplest way to do it. Add this static method to your enum:

public static int getIntValForString(String strVal) {
   for (MembershipTypes e : MembershipTypes.values()) {
      if (e.getStrVal().equals(strVal)) {
         return e.getIntVal();
      }
   }
   throw new IllegalArgumentException("No such enum for string val:" + strVal);
}


Use:

private static final Map<String, MEMBERSHIP_TYPES> MEMBERSHIP_TYPES = new HashMap<String, MembershipTypes>;
static {
  for (MembershipTypes membershipType : values()){
     MEMBERSHIP_TYPES.put(membershipType.strVal, membershipType);
  }
}

public static int getIntVal(String strVal){
  if (! MEMBERSHIP_TYPES.containsKey(strVal){
     throw new IllegalArgumentException("Unknown value: " + strVal);
  }
  return MEMBERSHIP_TYPES.get(strVal).getIntVal();
}

Consider:

  • renaming MembershipTypes to MembershipType
  • renaming intVal and strVal to more meaningful property names if possible


Your enum automatically gets a method valueOf(String) that returns the right enum when given an enum name. You can override that to also check for your strVal. Alternatively, you could write a utility function that returns the int value directly.


I think you can use ordinal().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜