how to print all enum value in java?

前端 未结 6 1009
自闭症患者
自闭症患者 2021-01-03 21:49
enum generalInformation {
    NAME {
        @Override
        public String toString() {
            return \"Name\";
        }
    },
    EDUCATION {
        @Over         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 22:16

    In applications, it's good practice to separate data from presentation. It allows the data to be used in different user interfaces, it makes the data objects more lightweight, and it allows for the future possibility of internationalization.

    With that in mind, it's good to avoid strongly coupling the display name to the enum constant. Fortunately, there is a class which makes this easy: EnumMap.

    public class ApplicationUI {
        private final Map names;
    
        public ApplicationUI() {
            names = new EnumMap<>(GeneralInformation.class);
    
            names.put(GeneralInformation.NAME,       "Name");
            names.put(GeneralInformation.EDUCATION,  "Education");
            names.put(GeneralInformation.EMAIL,      "Email");
            names.put(GeneralInformation.PROFESSION, "Profession");
            names.put(GeneralInformation.PHONE,      "Phone");
    
            assert names.keySet().containsAll(
                EnumSet.allOf(GeneralInformation.class)) :
                "Forgot to add one or more GeneralInformation names";
        }
    
        public String getNameFor(GeneralInformation info) {
            return names.get(info);
        }
    }
    

提交回复
热议问题