I use this technique frequently but I'm not sure what to call it. I call it associative enums. Is that correct?
Example:
public enum Genders {
Male("M"), Female("F"), Transgender("T"), Other("O"), Unknown("U");
private String code;
Genders(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public static Genders get(String code) {
for (Genders gender : values()) {
if (gender.getCode().equalsIgnoreCase(code)) {
return gender;
}
}
return null;
}
}
An enum pattern, in which each enumerated case is associated to an instance of a generic attribute class, is identified and implemented. It is particularly useful in situations where there is a finite number of cases and each case is characterized by a set of constants.
In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type.
Singleton Design Pattern is one of GOF (Gang of Four) design pattern. It comes under creational patterns. The main idea behind the Singleton is, create only one object of a specific class is ever created.
Java Enum name() MethodThe name() method of Enum class returns the name of this enum constant same as declared in its enum declaration. The toString() method is mostly used by programmers as it might return a more easy to use name as compared to the name() method.
I have a set of classes for doing this but I don't have a name for it other than Encodable
interface Encodable<T>{
T getCode();
}
public class EnumUtils{
public static <U, T extends Enum<T> & Encodable<U>> T getValueOf(
@Nonnull Class<T> enumClass,
@Nullable U code){
for (T e : enumClass.getEnumConstants()){
if (Objects.equal(e.getCode(), code))
return e;
}
throw new IllegalArgumentException("No enum found for " + code);
}
}
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