Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

java - 如何从Java中的字符串值获取枚举值?(How to get an enum value from a string value in Java?)

Say I have an enum which is just

(说我有一个枚举)

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example "A" which would be Blah.A .

(我想找到一个字符串的枚举值,例如"A"就是Blah.A)

How would it be possible to do this?

(怎么可能做到这一点?)

Is the Enum.valueOf() the method I need?

(Enum.valueOf()是我需要的方法吗?)

If so, how would I use this?

(如果是这样,我将如何使用它?)

  ask by Malachi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, Blah.valueOf("A") will give you Blah.A .

(是的, Blah.valueOf("A")将给您Blah.A)

Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException .

(请注意,名称必须完全匹配,包括大小写: Blah.valueOf("a")Blah.valueOf("A ")都抛出IllegalArgumentException 。)

The static methods valueOf() and values() are created at compile time and do not appear in source code.

(静态方法valueOf()values()在编译时创建,并且不会出现在源代码中。)

They do appear in Javadoc, though;

(但是,它们确实出现在Javadoc中。)

for example, Dialog.ModalityType shows both methods.

(例如, Dialog.ModalityType显示两个方法。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...