尝试在Java的运行时从枚举中获取关联的值 [英] Trying to get the associated value from an Enum at runtime in Java

查看:244
本文介绍了尝试在Java的运行时从枚举中获取关联的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想完成以下内容(我感兴趣的是inInt()方法)。有什么本土的方式来完成这个吗?如果没有,我如何获得与枚举值相关联的整数(像在C#中)?

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

谢谢

推荐答案

Java枚举不像C#枚举。它们是对象,而不仅仅是整数常量的名称。你可以做的最好的事情是查看对象的哈希代码,但是在相信你正在寻找的意义上,这不会给你任何真正有意义的/有用的信息。唯一真正的方法就是在你的示例代码中将一个属性分配给枚举和一个访问它的方法(通过一个方法或一个公共的final字段)。

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).

这篇关于尝试在Java的运行时从枚举中获取关联的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆