Reputation: 793
Consider following enums:
public enum AllColors {
WHITE,
RED,
GRAY,
GREEN,
BLUE,
BLACK
}
public enum GrayscaleColors {
WHITE,
GREY,
BLACK
}
There is a discrepancy between enums (GRAY/GREY) - but there is not way to catch this typo at compilation time. This can create trouble if the system is using DB storage or messaging and has to convert between enum values based on their value.
I wish I could do something like that:
public enum GrayscaleColors {
AllColors.WHITE,
AllColors.GRAY,
AllColors.BLACK
}
but that does not seem to be possible.
Upvotes: 0
Views: 67
Reputation: 140484
You can declare a constructor, and compare names in the constructor:
public enum GrayscaleColors {
WHITE(AllColors.WHITE),
GREY(AllColors.GRAY),
BLACK(AllColors.BLACK);
GrayscaleColors(AllColors ac) {
if (!name().equals(ac.name()) throw new IllegalArgumentException();
}
}
Alternatively, you can simply use AllColors.valueOf
:
public enum GrayscaleColors {
WHITE,
GREY,
BLACK;
GrayscaleColors() {
// Will throw if no corresponding name exists.
AllColors.valueOf(name());
}
}
Or, of course, you could write a unit test to check for matching names.
Upvotes: 4