Cannot access static field within enum initialiser

前端 未结 5 1352
谎友^
谎友^ 2021-01-07 06:14

In this code I get a compiler error, see comment:

 public enum Type {
   CHANGESET(\"changeset\"),
   NEW_TICKET(\"newticket\"),
   TICKET_CHANGED(\"editedti         


        
5条回答
  •  再見小時候
    2021-01-07 06:43

    How about this; doesn't require you to make code changes at two places which is kind of error prone IMO:

    enum Type {
    
        CHANGESET("changeset"),
        NEW_TICKET("newticket"),
        TICKET_CHANGED("editedticket"),
        CLOSED_TICKET("closedticket");
    
        private static final Map tracNameMap =
                                          new HashMap();
    
        private final String name;
    
        public Type typeForName(final String name) {
            if (tracNameMap.containsKey(name)) {
                return tracNameMap.get(name);
            } else {
                for (final Type t : Type.values()) {
                    if (t.name.equals(name)) {
                        tracNameMap.put(name, t);
                        return t;
                    }
                }
                throw new IllegalArgumentException("Invalid enum name");
            }
        }
    
        private Type(String name) {
            this.name = name;
        }
    
    }
    

提交回复
热议问题