Java Enum access to private instance variable

后端 未结 6 1818
名媛妹妹
名媛妹妹 2021-02-05 10:50

Consider the example:

enum SomeEnum {
    VALUE1(\"value1\"),
    VALUE2(\"value2\"),
    VALUE3(\"value3\")
    ;
    private String value;

    private SomeEnu         


        
6条回答
  •  囚心锁ツ
    2021-02-05 11:35

    No-one seems to have addressed the private aspect. My guess is that you're accessing the private field from a containing type - that your enum is actually a nested type, like this:

    class Test
    {
        static void Main() {
            // Entirely valid
            SomeEnum.VALUE1.value = "x";
        }
    
        enum SomeEnum {
            VALUE1("value1");
    
            private String value;
    
            private SomeEnum(final String value) {
                this.value = value;
            }
        }
    }
    

    That's entirely legitimate and normal - you can always access private members of a nested type from the containing type.

    If you make the enum a top-level type, you won't see this.

    As for changing values - as everyone else has said, VALUE1 is implicitly static and final, but that doesn't stop you from changing VALUE1.value. Again, this is entirely in accordance with how Java works elsewhere - if you have a static field of type List, you can still add entries to it, because that's not modifying the field itself.

    If you want to make SomeEnum properly immutable, make the value field final.

提交回复
热议问题