Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get enum value from property

I have an enum with values VALID and INVALID, which have a boolean property associated with them. I would like to get the enum value based on a boolean value I provide.

If it is true I should get VALID, if it is false I should get INVALID. I would like to do so in a getter method like the below, based on the value of the member variable

public boolean getCardValidityStatus() {
    return CardValidationStatus status = CardValidationStatus(this.mCardValidityStatus));
}

My code:

private enum CardValidationStatus {
    VALID(true),
    INVALID(false);

    private boolean isValid;
    CardValidationStatus(boolean isValid) {
        this.isValid = isValid;
    }
    public boolean getValidityStatus() {
        return this.isValid;
    }
}
like image 302
LetsamrIt Avatar asked Mar 05 '23 13:03

LetsamrIt


1 Answers

You're able to achieve that using a static lookup method in the enum itself:

private enum CardValidationStatus {
    VALID(true),
    INVALID(false);

    //...

    public static CardValidationStatus forBoolean(boolean status) {

        //this is simplistic given that it's a boolean-based lookup
        //but it can get complex, such as using a loop...
        return status ? VALID : INVALID; 
    }
}

And the appropriate status can be retrieved using:

public CardValidationStatus getCardValidityStatus() {
    return CardValidationStatus.forBoolean(this.mCardValidityStatus));
}
like image 171
ernest_k Avatar answered Mar 15 '23 10:03

ernest_k