Can I specify ordinal for enum in Java?

前端 未结 7 2014
时光说笑
时光说笑 2020-12-01 05:45

The ordinal() method returns the ordinal of an enum instance.
How can I set the ordinal for an enum?

相关标签:
7条回答
  • 2020-12-01 06:52

    You can update ordinal using reflection:

    private void setEnumOrdinal(Enum object, int ordinal) {
        Field field;
        try {
            field = object.getClass().getSuperclass().getDeclaredField("ordinal");
            field.setAccessible(true);
            field.set(object, ordinal);
        } catch (Exception ex) {
            throw new RuntimeException("Can't update enum ordinal: " + ex);
        }
    }
    
    0 讨论(0)
提交回复
热议问题