最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Java中如何实现字符串的枚举

Java crifan 1141浏览 0评论
折腾:
【未解决】Java给OkHttp加cookie出错:Cannot resolve symbol setCookiePolicy和Unknown class CookiePolicy.ACCEPT_ALL
期间,需要去把一个user-agent字符串:
public static String UserAgent_Mac_Chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
优化改造为更加完整的写法,变成字符串的枚举
java string enum
java – Best way to create enum of strings? – Stack Overflow
Java enum with string values – HowToDoInJava
How to get an enum value from a string value in Java? – Stack Overflow
Java 枚举(enum) 详解7种常见的用法 – 请叫我大师兄 – CSDN博客
Converting Strings to Enums in Java | Baeldung
【总结】
最后用代码:
//    public static String UserAgent_Mac_Chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";

    public enum UserAgent {
        MAC_CHROME("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"),
        MAC_SAFARI("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15")
        ;

        private String text;

        /**
         * @param text
         */
        UserAgent(final String text) {
            this.text = text;
        }

        public String getText() {
            return this.text;
        }

        /* (non-Javadoc)
         * @see java.lang.Enum#toString()
         */
        @Override
        public String toString() {
            return this.getText();
        }

        public static UserAgent fromString(String text) {
            for (UserAgent eachUaValue : UserAgent.values()) {
                if (eachUaValue.text.equalsIgnoreCase(text)) {
                    return eachUaValue;
                }
            }
            return null;
        }
    }
}
调用:
.header("User-Agent", CrifanUtil.UserAgent.MAC_CHROME.getText())
即可实现:此处的字符串的枚举
且还支持从字符串中生成枚举值
以及获取到枚举值的字符串。

转载请注明:在路上 » 【已解决】Java中如何实现字符串的枚举

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.184 seconds, using 22.04MB memory