从枚举序数转换为枚举类型 [英] Convert from enum ordinal to enum type
问题描述
我有枚举类型 ReportTypeEnum
,它在我所有类的方法之间传递,但我需要在 URL 上传递它,所以我使用 ordinal 方法来获取 int 值.在我的其他 JSP 页面中获取它后,我需要将它转换回 ReportTypeEnum
以便我可以继续传递它.
I've the enum type ReportTypeEnum
that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an ReportTypeEnum
so that I can continue passing it.
如何将序数转换为 ReportTypeEnum
?
使用 Java 6 SE.
Using Java 6 SE.
推荐答案
要将序数转换为其枚举表示,您可能需要这样做:
To convert an ordinal into its enum represantation you might want to do this:
ReportTypeEnum value = ReportTypeEnum.values()[ordinal];
请注意数组边界.
请注意,每次调用 values()
都会返回一个新克隆的数组,这可能会对性能产生负面影响.如果要经常调用它,您可能想要缓存该数组.
Note that every call to values()
returns a newly cloned array which might impact performance in a negative way. You may want to cache the array if it's going to be called often.
关于如何缓存 values()
的代码示例.
Code example on how to cache values()
.
编辑此答案以包含评论中给出的反馈
这篇关于从枚举序数转换为枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!