Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

java - Cannot refer to the static enum field within an initializer?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...