java运行时添加枚举值,尝试在Java的运行时从枚举中获取关联的值

java运行时添加枚举值,尝试在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
解决方案
【java运行时添加枚举值,尝试在Java的运行时从枚举中获取关联的值】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).

    推荐阅读