Java Convert String to Enum object
By:Roy.LiuLast updated:2019-08-17
In Java, you can use Enum valueOf() to convert a String to an Enum object, review the following case study :
1. Java Enum example
WhoisRIR.java
package com.mkyong.whois.utils; public enum WhoisRIR { ARIN("whois.arin.net"), RIPE("whois.ripe.net"), APNIC("whois.apnic.net"), AFRINIC("whois.afrinic.net"), LACNIC("whois.lacnic.net"), JPNIC("whois.nic.ad.jp"), KRNIC("whois.nic.or.kr"), CNNIC("ipwhois.cnnic.cn"), UNKNOWN(""); private String url; WhoisRIR(String url) { this.url = url; public String url() { return url;
2. Problem
Given a String “arin”, how to convert it back to the above Enum object?
TestEnum.java
package com.mkyong.whois.utils; public class TestEnum { public static void main(String[] args) { //How to convert this? WhoisRIR rir = "arin";
3. Solution
To solve it, you can use enum valueOf() function and convert a String to an Enum object.
TestEnum.java
package com.mkyong.whois.utils; import java.util.Locale; public class Test { public static void main(String[] args) { // Solution : Uses valueOf() System.out.println(WhoisRIR.valueOf("arin".toUpperCase())); // Recommended Solution : add locale WhoisRIR rir = WhoisRIR.valueOf("ripe".toUpperCase(Locale.ENGLISH)); System.out.println(rir); System.out.println(rir.url()); // Error, no enum constant, case sensitive //System.out.println(WhoisRIR.valueOf("arin"));
Output
ARIN RIPE whois.ripe.net
References
From:一号门
COMMENTS