问题
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;
}
}
回答1:
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));
}
回答2:
I would add a parse
method to your enum, which takes the boolean
, iterates over all the values and returns the one that matches, for example:
public CardValidationStatus parse(boolean isValid) {
for (CardValidationStatus cardValidationStatus : CardValidationStatus.values()) {
if (cardValidationStatus.getValidityStatus() == isValid) {
return cardValidationStatus;
}
}
throw new IllegalArgumentException();
}
回答3:
@ernest_k solution made this work, but I think that's not reliable solution.
You should always do code which is independent.
- Because his solution is hardcoded. What if values of
VALID
&INVALID
are changed. Will you change yourforBoolean
logics also? - Because he did not check what the Enum fields are holding inside it.
Reliable solution will be @DaveyDaveDave answer. This will also work when you have many status with VALID & INVAlID.
private enum CardValidationStatus {
VALID(true),
INVALID(false);
//...
public CardValidationStatus forBoolean(boolean isValid) {
for (CardValidationStatus cardValidationStatus : CardValidationStatus.values()) {
if (cardValidationStatus.getValidityStatus() == isValid) {
return cardValidationStatus;
}
}
throw new IllegalArgumentException();
}
}
Suggestion (Easiest way I think)
Why are you making Enum just for storing 2 boolean values?
Just make static boolean named by VALID
& INVALID
.
public static final boolean CARD_STATUS_VALID = true;
public static final boolean CARD_STATUS_INVALID = false;
if(cardStatus == CARD_STATUS_VALID){
// todo
}
来源:https://stackoverflow.com/questions/52004191/how-to-get-enum-value-from-property