Java Enum访问私有实例变量 [英] Java Enum access to private instance variable

查看:85
本文介绍了Java Enum访问私有实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑例子:

 枚举SomeEnum {
VALUE1(value1),
VALUE2 (value2),
VALUE3(value3)
;
private String value;

private SomeEnum(final String value){
this.value = value;
}

// toString
public String toString(){
return value;
}
}

我们如何做到这一点(和值真的更改)?

  SomeEnum.VALUE1.value =Value4; 
System.out.println(SomeEnum.VALUE1);

不是枚举实例是隐式的静态最终?另外,由于 private ,为什么我可以在其他类之外访问它?

解决方案

没有人似乎已经解决了私人方面。我的猜测是,你从一个包含的类型访问私有字段 - 你的枚举是实际上是一个嵌套类型,如下所示:

  class Test 
{
static void Main(){
//完全有效
SomeEnum.VALUE1.value =x;
}

枚举SomeEnum {
VALUE1(value1);

private String value;

private SomeEnum(final String value){
this.value = value;
}
}
}

这是完全合法和正常的 - 您可以永远从包含类型访问嵌套类型的私有成员。



如果您将枚举设置为顶级类型,则您将赢得



至于更改值 - 正如其他人所说, VALUE1 是隐式静态和最终的,但这并不妨碍您更改 VALUE1.value 。再次,这完全符合Java在其他地方的工作 - 如果你有一个类型为 List 的静态字段,你仍然可以添加条目,因为这不是修改<如果你想让 SomeEnum 正确地不变,请使 value field final


Consider the example:

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

    private SomeEnum(final String value) {
        this.value = value;
    }

    //toString
    public String toString() {
        return value;
    }
}

How come can we do this (and the value really changes)?

SomeEnum.VALUE1.value = "Value4";
System.out.println(SomeEnum.VALUE1);

Isn't that enum instance(s) are implicitly static and final? Also, since value is private, why can I access it outside other classes?

解决方案

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.

这篇关于Java Enum访问私有实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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