如何从 Java 枚举的 String 值中查找它?
我想从其字符串值(或可能任何其他值)查找枚举。 我已经尝试过以下代码,但它不允许初始化程序中的静态。 有简单的方法吗?
public enum Verbosity {
BRIEF, NORMAL, FULL;
private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();
private Verbosity() {
stringMap.put(this.toString(), this);
}
public static Verbosity getVerbosity(String key) {
return stringMap.get(key);
}
};
I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way?
public enum Verbosity {
BRIEF, NORMAL, FULL;
private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();
private Verbosity() {
stringMap.put(this.toString(), this);
}
public static Verbosity getVerbosity(String key) {
return stringMap.get(key);
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
使用为每个 Enum 自动创建的
valueOf
方法。对于任意值,从以下内容开始:
仅当您的探查器告诉您时才继续进行 Map 实现。
我知道它会迭代所有值,但只有 3 个枚举值,几乎不值得任何其他努力,事实上,除非你有很多值,否则我不会费心使用 Map,它会足够快。
Use the
valueOf
method which is automatically created for each Enum.For arbitrary values start with:
Only move on later to Map implementation if your profiler tells you to.
I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.
你很接近了。 对于任意值,请尝试如下操作:
You're close. For arbitrary values, try something like the following:
使用 Java 8,您可以通过以下方式实现:
with Java 8 you can achieve with this way:
@Lyle 的答案相当危险,我发现它不起作用,特别是如果您将枚举设置为静态内部类。 相反,我使用了类似的东西,它将在枚举之前加载 BootstrapSingleton 映射。
编辑 对于现代 JVM(JVM 1.6 或更高版本)来说,这不再是问题,但我确实认为 JRebel 仍然存在问题,但我还没有机会重新测试它< /em>.
首先加载我:
现在将其加载到枚举构造函数中:
如果您有一个内部枚举,您可以在枚举定义上方定义 Map,并且(理论上)应该在之前加载。
@Lyle's answer is rather dangerous and I have seen it not work particularly if you make the enum a static inner class. Instead I have used something like this which will load the BootstrapSingleton maps before the enums.
Edit this should not be a problem any more with modern JVMs (JVM 1.6 or greater) but I do think there are still issues with JRebel but I haven't had a chance to retest it.
Load me first:
Now load it in the enum constructor:
If you have an inner enum you can just define the Map above the enum definition and that (in theory) should get loaded before.
并且您不能使用 valueOf() ?
编辑:顺便说一句,没有什么可以阻止您在枚举中使用 static { } 。
And you can't use valueOf()?
Edit: Btw, there is nothing stopping you from using static { } in an enum.
如果它对其他人有帮助,我更喜欢的选项(此处未列出)使用 Guava 的地图功能:
默认情况下,您可以使用
null< /code>,您可以
抛出 IllegalArgumentException
或者您的fromString
可以返回一个Optional
,无论您喜欢什么行为。In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:
With the default you can use
null
, you canthrow IllegalArgumentException
or yourfromString
could return anOptional
, whatever behavior you prefer.从 java 8 开始,您可以在一行中初始化地图,而无需静态块
since java 8 you can initialize the map in a single line and without static block
也许,看看这个。 它对我有用。
其目的是使用“/red_color”查找“RED”。
如果
枚举
很多,声明一个静态映射
并仅将枚举
加载到其中一次会带来一些性能优势。请提出您的意见。
Perhaps, take a look at this. Its working for me.
The purpose of this is to lookup 'RED' with '/red_color'.
Declaring a
static map
and loading theenum
s into it only once would bring some performance benefits if theenum
s are many.Please put in your opinons.
如果您想要一个默认值并且不想构建查找映射,您可以创建一个静态方法来处理它。
此示例还处理预期名称以数字开头的查找。
如果您需要辅助值,您只需像其他一些答案一样首先构建查找映射。
If you want a default value and don't want to build lookup maps, you can create a static method to handle that.
This example also handles lookups where the expected name would start with a number.
If you need it on a secondary value, you would just build the lookup map first like in some of the other answers.
您可以将枚举定义为以下代码:
请参阅以下内容更多说明的链接
You can define your Enum as following code :
See following link for more clarification
您可以按照 Gareth Davis 和 Gareth Davis 的建议使用
Enum::valueOf()
函数。 Brad Mace 位于上面,但请确保您处理了如果所使用的字符串不存在于枚举中则会抛出的IllegalArgumentException
。You can use the
Enum::valueOf()
function as suggested by Gareth Davis & Brad Mace above, but make sure you handle theIllegalArgumentException
that would be thrown if the string used is not present in the enum.