1

我在项目工作期间在存储库中发现了这种类型的代码。该存储库运行良好......但是当我试图通过独立的测试运行来理解代码时......给出错误!

public enum Fruits {
    static {
        APPLE= new Fruits( "APPLE", 0 );
        BANANA = new Fruits( "BANANA", 1 );
       // and so on.
    }
}

我无法理解在枚举中调用枚举构造函数的含义,这也是在没有声明构造函数的情况下。

4

3 回答 3

6

我的猜测是,这实际上是反编译真实代码的产物。这不是有效的 Java 源代码,但实际上是编译器将为您创建的枚举:

public enum Fruits {
    APPLE, BANANA;
}
于 2012-11-10T15:25:29.370 回答
4

像往常一样,@JonSkeets 的直觉胜出。编译他提供的代码:

public enum Fruits {
  APPLE, BANANA;
}

jad然后用产量反编译:

public final class Fruits extends Enum
{

    public static Fruits[] values()
    {
        return (Fruits[])$VALUES.clone();
    }

    public static Fruits valueOf(String s)
    {
        return (Fruits)Enum.valueOf(Fruits, s);
    }

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

    public static final Fruits APPLE;
    public static final Fruits BANANA;
    private static final Fruits $VALUES[];

    static
    {
        APPLE = new Fruits("APPLE", 0);
        BANANA = new Fruits("BANANA", 1);
        $VALUES = (new Fruits[] {
            APPLE, BANANA
        });
    }
}

完整的示例说明了当您声明枚举时编译器为您所做的所有工作。请注意,正如@MarkoTopolnik 指出的那样,您不能自己执行此操作,仅仅是因为编译器不允许这样做。

于 2012-11-10T15:37:09.210 回答
-1
    public enum Fruits {
        APPLE("APPLE", 0 ), BANANA("BANANA", 1 );
        String text;
        int value;
        private Fruits(String text, int value){
             this.text = text;
             this.value = value;
        }
        public String getText(){
             return text;
        }
        public int getValue(){
             return value;
        }
    }

当您希望添加更多参数时,此概念很有用。

于 2012-11-10T15:29:08.900 回答