问题描述
说我有一个enum只是
Say I have an enum which is just
public enum Blah {
A, B, C, D
}
我希望找到一个字符串的枚举值,例如A
这将是 Blah.A
。怎么可能这样做?
and I would like to find the enum value of a string, for example "A"
which would be Blah.A
. How would it be possible to do this?
Enum.valueOf()
我需要的方法是什么?如果是这样,我将如何使用它?
Is the Enum.valueOf()
the method I need? If so, how would I use this?
推荐答案
是, Blah.valueOf(A)
会给你 Blah.A
。
请注意,名称必须是完全匹配,包括大小写: Blah.valueOf(a)
和 Blah.valueOf(A)
都抛出 IllegalArgumentException
。
Note that the name must be an exact match, including case: Blah.valueOf("a")
and Blah.valueOf("A ")
both throw an IllegalArgumentException
.
静态方法 valueOf()
和 values()
是在编译时创建的,不会出现在源代码中。但它们确实出现在Javadoc中;例如,显示两种方法。
The static methods valueOf()
and values()
are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType
shows both methods.
这篇关于如何从Java中的字符串值获取枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!