1

可能重复:
无法访问枚举初始化程序中的静态字段

我的情况:

enum Attribute { POSITIVE, NEGATIVE }
enum Content {
    C1(Attribute.POSITIVE),
    C2(Attribute.POSITIVE),
    ... // some other positive enum instances.
    Cm(Attribute.NEGATIVE),
    ... // some other negative enum instances.
    Cn(Attribute.NEGATIVE);

    private final Atrribute a;
    static int negativeOffset = 0;
    private Content(Atrribute a) {
        this.a = a;
        if ( a.compareTo(Attribute.POSITIVE) == 0 ) {
               negativeOffset ++;
        }
    }

    public static int getNegativeOffset() { return negativeOffset; }
} 

我的意图是每当我添加一个新的枚举(带有 POSITIVE 属性)时将负偏移量加一,然后我可以调用 getNegativeOffset() 来获取负枚举的起点并做任何我想做的事情。

但comlier抱怨说

Cannot refer to the static enum field Content.negativeOffset within an initializer

4

1 回答 1

2

你可以使用这个“技巧”:

private static class IntHolder {
    static int negativeOffset;
}

然后像这样引用变量:

IntHolder.negativeOffset ++;

return IntHolder.negativeOffset; 

这样做的原因是 JVM 保证在初始化IntHolder静态内部类时初始化变量,这在访问它之前不会发生。

整个类将如下所示,编译:

enum Attribute { POSITIVE, NEGATIVE }
enum Content {
    C1(Attribute.POSITIVE),
    C2(Attribute.POSITIVE),
    ... // some other positive enum instances.
    Cm(Attribute.NEGATIVE),
    ... // some other negative enum instances.
    Cn(Attribute.NEGATIVE);

    private final Attribute a;

    private static class IntHolder {
        static int negativeOffset;
    }

    private Content(Attribute a) {
        this.a = a;
        if ( a == Attribute.POSITIVE) {
               IntHolder.negativeOffset ++;
        }
    }

    public static int getNegativeOffset() { return IntHolder.negativeOffset; }
}

请注意拼写错误的更正以及使用而不是与Attribute枚举值进行更简单的比较==compareTo()

于 2012-12-14T04:56:34.577 回答