Java create enum from String
This question already has an answer here:
添加并使用这种方法
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
}
Enum does not have ready to use method for this. You either need to use exact field names:
PaymentType.valueOf("SUBSCRIPTION_MODIFY");
Or write your own method, for example:
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");
}
So this code:
public static void main(String[] args) {
System.out.println(PaymentType.fromString("subscr_modify"));
}
Prints:
SUBSCRIPTION_MODIFY
valueOf
returns the enum item whose identifier matches the string you passed in.
For instance:
PaymentType t = PaymentType.valueOf("SUBSCRIPTION_NEW");
If you want to get the enum item whose type
field matches a given string, write a static method on PaymentType
that loops through PaymentType.values()
and returns the matching item.
上一篇: 将字符串转换为枚举
下一篇: Java从String创建枚举