我有枚举类型ReportTypeEnum,在我所有的类的方法之间传递,但我需要在URL上传递这个,所以我使用序数方法来获得int值。在我的另一个JSP页面中获得它之后,我需要将它转换回ReportTypeEnum,以便我可以继续传递它。

如何将序数转换为ReportTypeEnum?

使用Java 6 SE。


当前回答

So one way is to doExampleEnum valueOfOrdinal = ExampleEnum.values()[ordinal]; which works and its easy, however, as mentioned before, ExampleEnum.values() returns a new cloned array for every call. That can be unnecessarily expensive. We can solve that by caching the array like so ExampleEnum[] values = values(). It is also "dangerous" to allow our cached array to be modified. Someone could write ExampleEnum.values[0] = ExampleEnum.type2; So I would make it private with an accessor method that does not do extra copying.

private enum ExampleEnum{
    type0, type1, type2, type3;
    private static final ExampleEnum[] values = values();
    public static ExampleEnum value(int ord) {
        return values[ord];
    }
}

您可以使用exampleenumeration .value(ordinal)来获取与ordinal关联的枚举值

其他回答

有一种简单和坏的方法,也有一种相当简单和正确的方法。

首先,简单的和坏的(这些通常很受欢迎)。枚举类方法通过values()方法返回所有可用实例的数组,您可以通过数组索引访问枚举对象。

RenderingMode mode = RenderingMode.values()[index];

//Enum Class somewhere else
public enum RenderingMode
{
    PLAYING,
    PREVIEW,
    VIEW_SOLUTION;    
    
}
    

//RenderingMode.values()[0] will return RenderingMode.PLAYING
//RenderingMode.values()[1] will return RenderingMode.PREVIEW
//Why this is bad? Because it is linked to order of declaration.

//If you later changed the order here, it will impact all your existing logic around this.
public enum RenderingMode
    {
        
        PREVIEW,
        VIEW_SOLUTION,
        PLAYING;    
        
    }
 //Now
//RenderingMode.values()[0] will return RenderingMode.PREVIEW
//RenderingMode.values()[1] will return RenderingMode.VIEW_SOLUTION

这是正确的做法。 在枚举类中创建一个静态方法fromInt。

public enum RenderingMode
{
    PLAYING,
    PREVIEW,
    VIEW_SOLUTION;

    public static RenderingModefromInt(int index)
    {
       //this is independent of order of declaration
        switch (index)
        {
            case 0: return PLAYING;
            case 1: return PREVIEW;
            case 2: return VIEW_SOLUTION;
        }
        //Consider throwing Exception here

        return null;
    }
}

如果我要大量使用values():

enum Suit {
   Hearts, Diamonds, Spades, Clubs;
   public static final Suit values[] = values();
}

同时wherever.java:

Suit suit = Suit.values[ordinal];

如果你想要数组是私有的,请自便:

private static final Suit values[] = values();
public static Suit get(int ordinal) { return values[ordinal]; }

...

Suit suit = Suit.get(ordinal);

注意数组的边界。

每个枚举都有name(),它给出一个包含枚举成员名称的字符串。

给定一个花色{红心,黑桃,梅花,方块},Suit.Heart.name()将给出红心。

每个枚举都有一个valueOf()方法,该方法接受一个枚举类型和一个字符串,以执行相反的操作:

枚举. valueof (Suit.class, "Heart")返回Suit.Heart。

我真搞不懂为什么会有人用序数。它可能会快几纳秒,但如果枚举成员发生变化,则不安全,因为另一个开发人员可能不知道某些代码依赖于序数值(特别是在问题中引用的JSP页面中,网络和数据库开销完全占据了时间,而不是使用整数而不是字符串)。

通过这种方式,您可以不依赖于编译时泛型解析(因此您可以随时创建枚举类实例,即使是使用class . formame创建的类型)

public Object getInstance(Class enumClazz, int ordinal) throws Exception {
    Object[] allEnums = enumClazz.getDeclaredMethod("values", Object[].class).invoke(null, null);
    return allEnums[ordinal];
}

我同意大多数人的观点,使用序数可能是一个坏主意。我通常通过给枚举一个私有构造函数来解决这个问题,该构造函数可以以一个DB值为例,然后创建一个静态fromDbValue函数,类似于Jan的回答。

public enum ReportTypeEnum {
    R1(1),
    R2(2),
    R3(3),
    R4(4),
    R5(5),
    R6(6),
    R7(7),
    R8(8);

    private static Logger log = LoggerFactory.getLogger(ReportEnumType.class);  
    private static Map<Integer, ReportTypeEnum> lookup;
    private Integer dbValue;

    private ReportTypeEnum(Integer dbValue) {
        this.dbValue = dbValue;
    }


    static {
        try {
            ReportTypeEnum[] vals = ReportTypeEnum.values();
            lookup = new HashMap<Integer, ReportTypeEnum>(vals.length);

            for (ReportTypeEnum  rpt: vals)
                lookup.put(rpt.getDbValue(), rpt);
         }
         catch (Exception e) {
             // Careful, if any exception is thrown out of a static block, the class
             // won't be initialized
             log.error("Unexpected exception initializing " + ReportTypeEnum.class, e);
         }
    }

    public static ReportTypeEnum fromDbValue(Integer dbValue) {
        return lookup.get(dbValue);
    }

    public Integer getDbValue() {
        return this.dbValue;
    }

}

现在您可以在不更改查找的情况下更改顺序,反之亦然。