Thursday 25 August 2016

Java create enum from String




I have enum class



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


When I try to create enum :



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



Java throws to me error :



IllegalArgumentException occured : No enum constant models.PaymentType.subscr_signup


How I can fix this?


Answer



add and use this method




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
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...