Java – how to get enumeration values from attributes

I have an enumeration with values valid and invalid, which has Boolean attributes associated with it I want to get the enumeration value based on the Boolean value I provide

If so, I should get valid. If so, I should get invalid I want to do this in the getter method 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;
    }
}

Solution

You can do this using the static lookup method in the enumeration 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 you can retrieve the appropriate status using the following methods:

public CardValidationStatus getCardValidityStatus() {
    return CardValidationStatus.forBoolean(this.mCardValidityStatus));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>