我有两个具有相同键但不同键值的 ENUM,如下所示:
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;
}
}
我想创建一个通用函数(printGenericEnumInfo
)来打印其中任何一个 ENUM 键。
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);
}
}
你能帮我怎么做吗?