Here is another demonstration of what you're looking for. The difference between this and previous solutions is that this one is more generic and reusable pattern. This in fact goes beyond the original problem, to show some other benefits of this approach. So you might just comment the bits you don't need. I also attach a unit test to demonstrate the behaviour.
So basically to look for name Apple
or APPLE
in one of these enums just write:
FruitVeg<?> fvg = getEnum("APPLE", Fruits.class, Vegetables.class);
FruitVeg<>
is an interface, which allows to also tap inside of Enum, this interface allows to do some very interesting things with enums below. Here are just some of the things you could do with that:
Enum.valueOf(fvg.getDeclaringClass(), fvg.name())
: returns enum Value e.g. APPLE
fvg.getRaw()
: returns enum Value e.g. APPLE
fvg.name()
: returns enum's String Name e.g. APPLE
fvg.getFriendlyName()
: e.g. Apple
fvg.getDeclaringClass()
: returns Class<Enum<?>>
e.g. class ox.dummy.dummyTest$Fruits
fvg.getClass()
: class ox.dummy.dummyTest$Fruits returns Class<?>
EnumSet.allOf(fvg.getDeclaringClass()))
: e.g. [APPLE, PEAR]
Here is code
@Test
public void doSimpleTest() throws Exception {
FruitVeg<?> fvg = getEnum("APPLE", Fruits.class, Vegetables.class);
log.info("{} : {} : {} : {} : {}", fvg.name(), fvg.getFriendlyName(), fvg.getClass(), fvg.getDeclaringClass(), EnumSet.allOf(fvg.getDeclaringClass()));
log.info("get enum: {} ", Enum.valueOf(fvg.getDeclaringClass(), fvg.name()));
}
public interface FruitVeg<T extends Enum<T>> {
String name();
String getFriendlyName();
Class<T> getDeclaringClass();
T getRaw();
}
enum Fruits implements FruitVeg<Fruits> {
APPLE("Apple"),
PEAR("Pear");
Fruits(String friendlyName) {
this.friendlyName = friendlyName;
}
private final String friendlyName;
@Override
public String getFriendlyName() {
return friendlyName;
}
@Override
public Fruits getRaw() {
return this;
}
}
enum Vegetables implements FruitVeg<Vegetables> {
CARROT("Carrot"),
LETTUCE("Lettuce");
Vegetables(String friendlyName) {
this.friendlyName = friendlyName;
}
private final String friendlyName;
@Override
public String getFriendlyName() {
return friendlyName;
}
@Override
public Vegetables getRaw() {
return this;
}
}
public static FruitVeg<?> getEnum(String name, Class<? extends FruitVeg<?>>... fvgClasses) {
for (Class<? extends FruitVeg<?>> fruitVegCLass : Arrays.asList(fvgClasses)) {
for (FruitVeg<?> fvg : fruitVegCLass.getEnumConstants()) {
if (name.equals(fvg.name()) || name.equals(fvg.getFriendlyName())) {
return fvg;
}
}
}
return null;
}