Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would this enum pattern be called?

Tags:

java

enums

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;
    }
}
like image 696
sproketboy Avatar asked Jun 11 '12 21:06

sproketboy


People also ask

What is enum pattern?

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.

What is an enum entry called?

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.

Is enum a design pattern?

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.

What is enum name in Java?

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.


1 Answers

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);
      }
}
like image 76
John B Avatar answered Oct 13 '22 12:10

John B