Cannot access static field within enum initialiser

前端 未结 5 1339
谎友^
谎友^ 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:48

    The map is probably overkill here. Unless you are planning on having many more than four enum values you can implement getByTracName(String tn) by simply iterating over the valid strings and returning the correct one. If the map keys are always the enum names then you can do:

    public enum Type {
    CHANGESET,
    NEW_TICKET,
    TICKET_CHANGED,
    CLOSED_TICKET;
    
    private static final Map tracNameMap = new HashMap();
    static {
        for (Type t:Type.values()) {
            tracNameMap.put(t.name(), t);
        }
    }
    public static Type getByTracName(String tn) {
        return tracNameMap.get(tracNameMap);
    }
    

    }

    or you can do:

    public static Type getByTracName(String tn) {
      return Enum.valueOf(Type.class,tn);
    }
    

提交回复
热议问题