Cannot refer to the static enum field within an initializer?

前端 未结 2 1256
庸人自扰
庸人自扰 2020-12-14 00:09

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 compil

2条回答
  •  不知归路
    2020-12-14 00:49

    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 lowerCaseMap = new HashMap<>();
            private static int COUNTER = 0;
        }
    
        private Foo() {
            StaticFields.lowerCaseMap.put(this.name().toLowerCase(), this);
            StaticFields.COUNTER++;
        }
    }
    

提交回复
热议问题