Java create enum from String
本问题已经有最佳答案,请猛点这里访问。
我有枚举类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | public enum PaymentType { /** * This notify type we receive when user make first subscription payment. */ SUBSCRIPTION_NEW("subscr_signup"), /** * This notify type we receive when user make subscription payment for next * month. */ SUBSCRIPTION_PAYMENT("subscr_payment"), /** * This notify type we receive when user cancel subscription from his paypal * personal account. */ SUBSCRIPTION_CANCEL("subscr_cancel"), /** * In this case the user cannot change the amount or length of the * subscription, they can however change the funding source or address * associated with their account. Those actions will generate the * subscr_modify IPN that we are receiving. */ SUBSCRIPTION_MODIFY("subscr_modify"), /** * Means that the subscription has expired, either because the subscriber * cancelled it or it has a fixed term (implying a fixed number of payments) * and it has now expired with no further payments being due. It is sent at * the end of the term, instead of any payment that would otherwise have * been due on that date. */ SUBSCRIPTION_EXPIRED("subscr_eot"), /** User have no money on card, CVV error, another negative errors. */ SUBSCRIPTION_FAILED("subscr_failed"); private String type; PaymentType(String type) { this.type = type; } String getType() { return type; } } |
尝试创建枚举时:
1 | PaymentType type = PaymentType.valueOf("subscr_signup"); |
Java向我抛出错误:
1 |
我怎么能解决这个问题?
添加并使用此方法
1 2 3 4 5 6 7 8 | public static PaymentType parse(String type) { for (PaymentType paymentType : PaymentType.values()) { if (paymentType.getType().equals(type)) { return paymentType; } } return null; //or you can throw exception } |
枚举尚未准备好对此使用方法。您要么需要使用准确的字段名:
1 | PaymentType.valueOf("SUBSCRIPTION_MODIFY"); |
或者编写自己的方法,例如:
1 2 3 4 5 6 7 8 | public static PaymentType fromString(String string) { for (PaymentType pt : values()) { if (pt.getType().equals(string)) { return pt; } } throw new NoSuchElementException("Element with string" + string +" has not been found"); } |
所以这个代码:
1 2 3 |
印刷品:
1 | SUBSCRIPTION_MODIFY |
1 | subscr_signup |
是枚举变量值,而不是枚举值。因此,如果要根据枚举的值名称获取枚举,则必须这样做:
1 | PaymentType type = PaymentType.valueOf("SUBSCRIPTION_NEW"); |
您需要编写一个静态方法,该方法为给定值返回正确的枚举实例。例如:
1 2 3 4 5 6 7 8 | public static PaymentType byTypeString(String type) { for (PaymentType instance : values()) { if (instance.type.equals(type)) { return instance; } } throw new IllegalArgumentException("No PaymentType enum instance for type:" + type); } |
1 | PaymentType t = PaymentType.valueOf("SUBSCRIPTION_NEW"); |
如果要获取其