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;
}
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With