如何正确扩展Enum

时间:2014-05-27 21:32:08

标签: java android enums

当我使用这个类时,它会显示一些错误。

类别:

public static final class ScreenOrientation extends Enum
    {

        private static final ScreenOrientation ENUM$VALUES[];
        public static final ScreenOrientation LANDSCAPE_FIXED;
        public static final ScreenOrientation LANDSCAPE_SENSOR;
        public static final ScreenOrientation PORTRAIT_FIXED;
        public static final ScreenOrientation PORTRAIT_SENSOR;

        public static ScreenOrientation valueOf(String s)
        {
            return (ScreenOrientation)Enum.valueOf(org/andengine/engine/options/EngineOptions$ScreenOrientation, s);
        }

        public static ScreenOrientation[] values()
        {
            ScreenOrientation ascreenorientation[] = ENUM$VALUES;
            int i = ascreenorientation.length;
            ScreenOrientation ascreenorientation1[] = new ScreenOrientation[i];
            System.arraycopy(ascreenorientation, 0, ascreenorientation1, 0, i);
            return ascreenorientation1;
        }

        static 
        {
            LANDSCAPE_FIXED = new ScreenOrientation("LANDSCAPE_FIXED", 0);
            LANDSCAPE_SENSOR = new ScreenOrientation("LANDSCAPE_SENSOR", 1);
            PORTRAIT_FIXED = new ScreenOrientation("PORTRAIT_FIXED", 2);
            PORTRAIT_SENSOR = new ScreenOrientation("PORTRAIT_SENSOR", 3);
            ScreenOrientation ascreenorientation[] = new ScreenOrientation[4];
            ascreenorientation[0] = LANDSCAPE_FIXED;
            ascreenorientation[1] = LANDSCAPE_SENSOR;
            ascreenorientation[2] = PORTRAIT_FIXED;
            ascreenorientation[3] = PORTRAIT_SENSOR;
            ENUM$VALUES = ascreenorientation;
        }

        private ScreenOrientation(String s, int i)
        {
            super(s, i);
        }
    }

展开Enum时,会显示The type q may not subclass Enum explicitly错误。

如何使用这些字段创建枚举?
如何修改此类以使用Enum

1 个答案:

答案 0 :(得分:4)

public enum ScreenOrientation {

    LANDSCAPE_FIXED("LANDSCAPE_FIXED", 0);
    // other values

    private final String s;
    private final int i;

    private ScreenOrientation(String s, int i) {
        this.s = s;
        this.i = i;
    }

    // getters for s and i

    @Override
    public String toString() { 
        return this.getS();
    }

    public static ScreenOrientation fromS(String s) {
        for( ScreenOrientation so : values())
            if(so.getS().equalsIgnoreCase(s)) {
                return so;
        }
       throw new IllegalArgumentException();
    }
}

不确定s和i等于什么,所以给他们更有意义的名字。另外,按照Javadocs中的建议覆盖toString方法:

http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#name()