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).
推荐阅读
- java|Meta元宇宙OS要黄(300人研发团队解散,关闭VR/AR操作系统研发)
- 为什么java首次运行慢_第一次Java循环运行缓慢,为什么([Sun HotSpot 1.5,sparc])
- java操作es聚合操作并显示其他字段_javaAPI操作ES分组聚合
- java怎么创建日期_用户如何在我的日历(java)中创建日期()
- star法则java简历_在简历中使用STAR法则
- java|改名Meta俩月,脸书放弃虚拟现实操作系统(负责人跳槽谷歌)
- GWA2 Java 增加多线程数据共享通道 globalData
- JavaScript|JavaScript 自定义对象
- java增删改一键生成_Java代码自动生成,生成前端vue+后端controller、service、dao代码,根据表名自动生成增删改查功能...
- vue和java实现页面增删改_Spring boot + mybatis + Vue.js + ElementUI 实现数据的增删改查实例代码(一)...