无法引用初始化程序中的静态枚举字段? [英] Cannot refer to the static enum field within an initializer?

查看:437
本文介绍了无法引用初始化程序中的静态枚举字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚有Java5项目有这个错误,我尝试使用Java5和Java6,但它仍然存在。它的工作原理(因为它在svn),我怎么可以绕过编译器错误?

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?

推荐答案

错误 - 它不会做你想要的。错误是有很好的理由。

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 after everything 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);
        }
    }
}

这篇关于无法引用初始化程序中的静态枚举字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆