javaenums

Java ENUM Generic Function


I have two ENUM with same keys but different keyValues as follows:

enum STUDENT_INFO {
    NAME("Student Name"),
    AGE("Age"),
    DOB("Date of Birth"),
    SEX("Sex"),
    LOCATION1("Hostel Info"),
    LOCATION2("Permanent Address"),
    ID("Institution ID"),
    INSTITUTE("Institution Name");

    private final String enumKey;
    STUDENT_INFO(String enumKey) {
        this.enumKey = enumKey;
    }
    public String getEnumKey() {
        return enumKey;
    }
}

enum PERSON_INFO {
    NAME("Person Name"),
    AGE("Age"),
    DOB("Date of Birth"),
    SEX("Sex"),
    LOCATION1("Present Address"),
    LOCATION2("Permanent Address"),
    ID("Person ID"),
    INSTITUTE("Job Name");

    private final String enumKey;
    PERSON_INFO(String enumKey) {
        this.enumKey = enumKey;
    }
    public String getEnumKey() {
        return enumKey;
    }
}

I want to Create a generic function (printGenericEnumInfo) to print anyone of those ENUM Keys.

class JavaTest {
    public static void printStudentEnumInfo() {
        System.out.println(STUDENT_INFO.NAME.getEnumKey());
        System.out.println(STUDENT_INFO.LOCATION1.getEnumKey());
        System.out.println(STUDENT_INFO.LOCATION2.getEnumKey());
    }

    // Generic Method to Print Enum Keys
    public static void printGenericEnumInfo(Enum<T> enumName) {
        System.out.println(enumName.NAME.getEnumKey());
        System.out.println(enumName.LOCATION1.getEnumKey());
        System.out.println(enumName.LOCATION2.getEnumKey());
    }
}

public class Main {
    public static void main(String[] args) {
        // Working perfectly
        JavaTest.printStudentEnumInfo();

        // How to implement this
        JavaTest.printGenericEnumInfo(STUDENT_INFO);
        JavaTest.printGenericEnumInfo(PERSON_INFO);
    }
}

Can you help me how to do this ?

Demo Code: tutorialspoint_JavaCompiler


Solution

  • The two enums should both implement such an interface:

    interface HasEnumKey {
        String getEnumKey();
    }
    
    enum STUDENT_INFO implements HasEnumKey { ... }
    enum PERSON_INFO implements HasEnumKey { ... }
    

    Then the method can take a Class<T> representing the enum class. Constrain T to be an enum and to implement HasEnumKey,

    static <T extends Enum<T> & HasEnumKey> void printGenericEnumInfo(Class<T> enumClass) {
        for (T value: enumClass.getEnumConstants()) {
            System.out.println(value.getEnumKey());
        }
    }
    

    Usage:

    printGenericEnumInfo(STUDENT_INFO.class);