模拟一类枚举类型

时间:2010-08-19 09:37:46

标签: java class enums simulate

如何在java< 5.0 .. ??

中模拟一个类型的枚举类
public final class Week {

    private static final Day[] _week = {Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY, Day.SATURDAY, Day.SUNDAY};

    public static Day getDayOfWeek(final int index) {
        if (index >= 1 && index <= 7) {
            return _week[index - 1];
        }
        throw new IndexOutOfBoundsException("Invalid index [1..7]");
    }

    public static final class Day {
        public static final Day MONDAY = new Day(1, "Monday");
        public static final Day TUESDAY = new Day(2, "Tuesday");
        public static final Day WEDNESDAY = new Day(3, "Wednesday");
        public static final Day THURSDAY = new Day(4, "Thursday");
        public static final Day FRIDAY = new Day(5, "Friday");
        public static final Day SATURDAY = new Day(6, "Saturday");
        public static final Day SUNDAY = new Day(7, "Sunday");

        private int _value;
        private String _name;

        private Day(final int value, final String name) {
            _value = value;
            _name = name;
        }

        /* (non-Javadoc)
         * @see java.lang.Object#toString()
         */
        public String toString() {
            return "[Day] " + _name;
        }

        /* (non-Javadoc)
         * @see java.lang.String#equals(java.lang.Object)
         */
        public boolean equals(Object anObject) {
            Day d = (Day)anObject;
            return _value == d._value;
        }
    }

    public static void main(String[] agrs) {
         System.out.println(Week.getDayOfWeek(2));
    }
}

4 个答案:

答案 0 :(得分:4)

很久以前,约书亚布洛赫写道an article解释它。

答案 1 :(得分:4)

使用有效java中描述的typesafe枚举。以下是Joshua Blochs article on this给出的示例:

// The typesafe enum pattern
public class Suit {
    private final String name;

    private Suit(String name) { this.name = name; }

    public String toString()  { return name; }

    public static final Suit CLUBS =
        new Suit("clubs");
    public static final Suit DIAMONDS =
        new Suit("diamonds");
    public static final Suit HEARTS =
        new Suit("hearts");
    public static final Suit SPADES =
        new Suit("spades");
}

如果您希望类型安全枚举为Serializable,请记住通过readResolve方法控制重建。

答案 2 :(得分:0)

Joshua Bloch向您展示了他的“Effective Java”的第一版。我必须去上班,所以我现在不能输入细节。更多要关注。

答案 3 :(得分:0)

Krock和Riduidel建议的解决方案非常简洁,但AFAIK switch-case声明是不可能的,因为它仅适用于可转换int值和enum常量。 switch-case组合是一个很好的功能,比一堆if更易读(BTW:switch-case无论如何都会被编译成一堆if,对吗?)。那么,为了完成讨论的模式,有人可以判断是否有一种快速的方法来启用这个功能允许switch-case的功能?添加int属性和getter似乎是最简单的方法,但它是最优的吗?