开发者

Trying to get the associated value from an Enum at runtime in Java

I want to accomplish something like the following (my interest is in the toInt() method). Is there any native way to accomplish this? If not, how can I get the integer associated with an enum value (like in C#) ?

enum Rate {
 VeryBad(1),
 Bad(2),
 Average(3),开发者_运维问答
 Good(4),
 Excellent(5);

 private int rate;

 private Rate(int rate) {
  this.rate = rate;
 }

 public int toInt() {
  return rate;
 }
}

Thanks


In "Effective Java" Joshua Bloch recommends the following pattern:

private static final Map<Integer, Rate> intToEnum = new HashMap<Integer, Rate>();
static
{
   for(Rate rate: values())
      intToEnum.put(Integer.valueOf(rate.toInt()), rate);
}
public static Rate fromInt(int intVal)
{
   return intToEnum.get(Integer.valueOf(intVal));
}


Java enums are not like C# enums. They are objects as opposed to just a name for an integer constant. The best you could do is look at the hash code for the objects, but that will not give you any real meaningful/ useful information in the sense I believe you are looking for. The only real way to do it is as in your example code assigning a property to the enum and a means for accessing it (either via a method, or as a public final field).


return enumVal.ordinal();

(see the javadoc)

Edit: I originally misread your code; you seem to be doing all the int/enum conversion stuff manually, when Java handles all that. You really shouldn't need to use ints, you can just use the enums as a separate type. As the javadoc says, it's unlikely you'll ever actually want the int associated with a particular value; "Good" and "4" don't have any connection to each other, 4 just happens to be its position in the enum


Not sure if this answers your question but an enum instance has an ordinal() method returning its position as an int. But it is bad practice to rely on it, the instance field as shown in your example is the way to go...


As enum is treated as an object in Java. To get the value ofrrate associated with your enum just write the following code

return enumValue.toInt();

In this case enumValue stored the current enum instance. So for example

Rate enumValue = Rate.Good;
enumValue.toInt(); // return value 4;

Alternatively if you want to know what is its ordinal then return enumValue.ordinal(); However after assigning some value to an enum I do not understand why you would need its ordinal.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜