I have several enums with a name
property and a byName
method which is roughly like this for all of them:
public static Condition byName(String name) throws NotFoundException {
for (Condition c : values()) {
if (c.name.equals(name)) {
return c;
}
}
throw new NotFoundException("Condition with name [" + name + "] not found");
}
Since the byName
method is duplicated across different enums, I'd like to factor it out in a single place and avoid duplicated code.
However:
values()
methodI know this could probably be done with AspectJ, but I'd rather not introduce compile-time weaving for something simple as this, and Spring AOP (which I have at hand since this is a Spring project) only allows binding to existing methods and not adding new ones.
Any other viable solution to add a common method to enums?
Here's what I did in the same situation:
public interface EnumWithNames {
String getName();
static <E extends EnumWithNames> E byName(Class<E> cls, String name) {
for (E value : cls.getEnumConstants()) {
if (Objects.equals(value.getName(), name)) return value;
}
throw new IllegalArgumentException("cannot identify " + cls.getName() + " value by name " + name);
}
}
public enum Condition implements EnumWithNames {
private String name;
...
@Override
public String getName() { return name; }
}
And when I need to find enum value by name I call:
Condition c = EnumWithNames.byName(Condition.class, "Name 1");
Note cls.getEnumConstants()
is the same as values()
.
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