Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can we get enum's value if string matches or get default in Java?

I have an enum class looking like below

@Slf4j
public enum PGPaymentStatus {

    ACTIVE(true) {
        @Override
        public <T> T accept(PaymentStatusVisitor<T> visitor) {
            return visitor.visitActive();
        }
    },
    PAID(false) {
        @Override
        public <T> T accept(PaymentStatusVisitor<T> visitor) {
            return visitor.visitPaid();
        }
    },
    EXPIRED(false) {
        @Override
        public <T> T accept(PaymentStatusVisitor<T> visitor) {
            return visitor.visitExpired();
        }
    },

    UNKNOWN(true) {
        @Override
        public <T> T accept(PaymentStatusVisitor<T> visitor) {
            return visitor.visitUnknown();
        }
    };

    public final boolean active;

    PGPaymentStatus(boolean active) {
        this.active = active;
    }

    public abstract <T> T accept(PaymentStatusVisitor<T> visitor);

    public interface PaymentStatusVisitor<T> {
        T visitActive();

        T visitPaid();

        T visitExpired();

        default T visitUnknown() {
            log.error("Unknown state received from payment gateway");
            return null;
        }
    }
}

I am trying to translate java.lang.String to PGPaymentStatus enum using valueOf method as shown below.

PGPaymentStatus.valueOf(createOrderResponse.getOrderStatus())

Is there a way to get default UNKNOWN value from valueOf method or any other alternate when order status string doesn’t match any of the enums present?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The first option is to prepare a method that will iterate enum values and return default if not present:

public static PGPaymentStatus iterationFindByName(String name) {
    for (PGPaymentStatus status : PGPaymentStatus.values()) {
        if (name.equals(status.name())) {
            return status;
        }
    }
    return PGPaymentStatus.UNKNOWN;
}

The more elegant way is using the Guava library Enums.getIfPresent method.

Enums.getIfPresent(PGPaymentStatus.class, name).orElse(PGPaymentStatus.UNKNOWN);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading