What will this listing template be?

I often use this technique, but I'm not sure what to call it. I call it associative enumerations. It is right?

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; } } 
+6
source share
3 answers

I would say that it looks pretty similar to the Multiton Pattern . If you do as erikb suggests and use a map instead of a loop, I would say it exactly the same as in the Multiton Pattern.

+2
source

I have a set of classes for this, but I have no name for it except 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); } } 
+3
source

I would say that it is a very simple and simple parser.

+1
source

Source: https://habr.com/ru/post/917831/


All Articles