Java – Convert String To Enum Object
来源:互联网 发布:在联通云数据工作好吗 编辑:程序博客网 时间:2024/05/21 21:52
Review below Java enum example, how to convert a String like ‘arin’ to WhoisRIR.ARIN
Enum object?
1. Problem
WhoisRIR rir = //convert 'arin' to enum WhoisRIR.ARIN ?
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"), //should query apnicUNKNOWN(""); private String url; private WhoisRIR(String url) {this.url = url;} public String getUrl() {return url;} }
2. Solution
To solve it, use enum valueOf()
and convert the String to uppercase and set a default locale.
TestEnum.java
package com.mkyong.whois.utils; import java.util.Locale; public class TestEnum { public static void main(String[] args) { //Solution : Uses valueOf()System.out.println(WhoisRIR.valueOf("arin".toUpperCase())); //Recommended Solution : add localeWhoisRIR rir = WhoisRIR.valueOf("ripe".toUpperCase(Locale.ENGLISH));System.out.println(rir);System.out.println(rir.getUrl()); } }
Output
ARINRIPEwhois.ripe.net
Test it again, without convert to uppercase :
TestEnum.java
package com.mkyong.whois.utils; import java.util.Locale; public class TestEnum { public static void main(String[] args) { //error, need convert the String to uppercaseSystem.out.println(WhoisRIR.valueOf("arin")); } }
Output
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.mkyong.whois.utils.WhoisRIR.arin at java.lang.Enum.valueOf(Unknown Source)at com.mkyong.whois.utils.WhoisRIR.valueOf(WhoisRIR.java:1)at com.mkyong.whois.utils.TestEnum.main(TestEnum.java:17)
http://www.mkyong.com/java/java-convert-string-to-enum-object/
0 1
- Java – Convert String To Enum Object
- Object convert to Json string
- Convert string to object (c#)
- Convert a string to an enum
- Java – Convert String to int
- Java Convert ArrayList<String> to String []
- convert Java object to / from JSON
- Type mismatch: cannot convert from Object to String
- Type mismatch: cannot convert from Enumeration<String> to Enumeration<Object>
- Type mismatch: cannot convert from Object to String
- How to convert Java String into byte[]?
- How to convert Java object to / from JSON (Gson)
- How to convert Java object to / from JSON (Gson)
- java bean convert to json string and json string convert to java bean
- Java JSON - Convert Java Object To / From JSON (Jackson)
- ios enum to string
- string Convert To XML
- CONVERT to String
- 12.1 生成序列
- Linux下 Mini-shell的实现(C/C++)
- Managed Metadata Service Application(一)创建Managed Metadata Service Application
- zinnia下user各自的category
- BJFU-ACM-1009 抽奖
- Java – Convert String To Enum Object
- poj3107--Godfather(树形DP练习3)
- 【C语言】01-类型总结
- WV.10-动态链表-搜索某值存在个数
- 机器学习基础(三)Logistic回归模型
- 二叉树的宽度和深度
- 实现方式二:隐藏TabWidget,通过RadioGroup和RadioButton实现底部菜单栏
- 帮你理清Java中字符与字节的编码关系
- hiho-最长回文子串