天天看點

java 枚舉 建立_從字元串建立Java枚舉

本問題已經有最佳答案,請猛點這裡通路。

我有枚舉類

public enum PaymentType {

SUBSCRIPTION_NEW("subscr_signup"),

SUBSCRIPTION_PAYMENT("subscr_payment"),

SUBSCRIPTION_CANCEL("subscr_cancel"),

SUBSCRIPTION_MODIFY("subscr_modify"),

SUBSCRIPTION_EXPIRED("subscr_eot"),

SUBSCRIPTION_FAILED("subscr_failed");

private String type;

PaymentType(String type) {

this.type = type;

}

String getType() {

return type;

}

}

嘗試建立枚舉時:

PaymentType type = PaymentType.valueOf("subscr_signup");

Java向我抛出錯誤:

IllegalArgumentException occured : No enum constant models.PaymentType.subscr_signup

我怎麼能解決這個問題?

我認為您必須在枚舉中編寫一個比較方法

stackoverflow.com/a/2965252/5188230

建立額外的靜态方法,該方法将搜尋枚舉的值

@不是複制品。如果字元串不是同一枚舉值,則提供的示例不是解決方案。

@Gregkopff提供了正确的答案。

@ssh你讀過所提供問題的第二個答案了嗎?

@ssh您可能希望滾動一點,而不僅僅是為了獲得已接受的答案。

@謝謝你。那是我要找的!

添加并使用此方法

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

}

對。它是正确的。

枚舉尚未準備好對此使用方法。您要麼需要使用準确的字段名:

PaymentType.valueOf("SUBSCRIPTION_MODIFY");

或者編寫自己的方法,例如:

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");

}

是以這個代碼:

public static void main(String[] args) {

System.out.println(PaymentType.fromString("subscr_modify"));

}

印刷品:

SUBSCRIPTION_MODIFY

subscr_signup

是枚舉變量值,而不是枚舉值。是以,如果要根據枚舉的值名稱擷取枚舉,則必須這樣做:

PaymentType type = PaymentType.valueOf("SUBSCRIPTION_NEW");

Enum類.valueOf()方法将傳遞給它的字元串與枚舉執行個體的name屬性(執行個體名稱的實際值)進行比較,是以在您的示例中,這将是"SUBSCRIPTION_NEW"而不是"subscr_signup"。

您需要編寫一個靜态方法,該方法為給定值傳回正确的枚舉執行個體。例如:

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);

}

我不能用它。

為什麼不?如果不能修改paymentType枚舉,隻需将其作為靜态方法添加到其他地方,使用getType()通路器而不是直接使用type。

valueOf傳回其辨別符與您傳入的字元串比對的枚舉項。例如:

PaymentType t = PaymentType.valueOf("SUBSCRIPTION_NEW");

如果要擷取其type字段與給定字元串比對的枚舉項,請在PaymentType上編寫一個靜态方法,該方法通過PaymentType.values()循環并傳回比對項。

我不能用它,因為我不能改變常量。

當然你可以寫一個方法。