java 无法在初始化程序中引用静态枚举字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/536449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:47:00  来源:igfitidea点击:

Cannot refer to the static enum field within an initializer?

javacompiler-construction

提问by IAdapter

I just got Java5 project that has this error, i tried using Java5 and Java6, but its still there. it worked somehow before(since it was in svn), how can i bypass that compiler error?

我刚刚收到出现此错误的 Java5 项目,我尝试使用 Java5 和 Java6,但它仍然存在。它以前以某种方式工作(因为它在 svn 中),我如何绕过该编译器错误?

回答by Jon Skeet

Don't "bypass" the error - it won't do what you want it to. The error is there for good reason.

不要“绕过”错误 - 它不会做你想要的。错误是有充分理由的。

The enum values are initialized before any other static fields. If you want to do something like adding all the values into a map, do it in a static initializer aftereverything else:

枚举值在任何其他静态字段之前初始化。如果你想要做的事,如添加的所有值到一个地图,做一个静态初始化一切:

import java.util.*;

public enum Foo
{
    BAR, BAZ;

    private static final Map<String, Foo> lowerCaseMap;

    static
    {
        lowerCaseMap = new HashMap<String, Foo>();
        for (Foo foo : EnumSet.allOf(Foo.class))
        {
            // Yes, use some appropriate locale in production code :)
            lowerCaseMap.put(foo.name().toLowerCase(), foo);
        }
    }
}

回答by Luan Nico

Another way to "bypass" it, if you need for example a counter or something that needs to run on each initalization, is to create a private static inner class, like so:

“绕过”它的另一种方法,例如,如果您需要一个计数器或需要在每次初始化时运行的东西,则创建一个私有静态内部类,如下所示:

public enum Foo {
    BAR, BAZ;

    private static final class StaticFields {
        private static final Map<String, Foo> lowerCaseMap = new HashMap<>();
        private static int COUNTER = 0;
    }

    private Foo() {
        StaticFields.lowerCaseMap.put(this.name().toLowerCase(), this);
        StaticFields.COUNTER++;
    }
}