Cannot refer to the static enum field within an initializer?

JavaCompiler Construction

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIAdapterView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaLuan NicoView Answer on Stackoverflow