无法访问枚举初始化程序中的静态字段 [英] Cannot access static field within enum initialiser

查看:252
本文介绍了无法访问枚举初始化程序中的静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我收到一个编译器错误,请参阅注释:

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

 public enum Type {
   CHANGESET("changeset"),
   NEW_TICKET("newticket"),
   TICKET_CHANGED("editedticket"),
   CLOSED_TICKET("closedticket");

   private static final Map<String, Type> tracNameMap = new HashMap<String, Type>();

   private Type(String name) {
    tracNameMap.put(name, this); // cannot refer to static field within an initializer
   }

   public static Type getByTracName(String tn) {
    return tracNameMap.get(tracNameMap);
   }

  }

有没有办法让这个工作,通过其一个字段从映射获取枚举值

Is there a way to make this work, getting an enum value from a Map by one of its fields?

推荐答案

这里的地图可能太过分了。除非你计划拥有多个四个枚举值,否则可以通过简单地迭代有效的字符串并返回正确的值来实现getByTracName(String tn)。如果地图键始终是枚举名称,那么您可以执行以下操作:

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<String, Type> tracNameMap = new HashMap<String, Type>();
static {
    for (Type t:Type.values()) {
        tracNameMap.put(t.name(), t);
    }
}
public static Type getByTracName(String tn) {
    return tracNameMap.get(tracNameMap);
}

}

或者你可以做:

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

这篇关于无法访问枚举初始化程序中的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆