从枚举访问超类变量



有没有办法从枚举本身中设置枚举父/超类中保存的变量? (以下内容没有编译,但说明了我试图实现的目标)....

class MyClass{
    ObjectType type;        
    String someValue;

    public void setType(ObjectType thisType){
        type = thisType;
    } 
    enum ObjectType {
        ball{
            @Override
            public void setValue(){
                someValue = "This is a ball";  //Some value isn't accessible from here
            }
        },
        bat{
            @Override
            public void setValue(){
                someValue = "This is a bat";  //Some value isn't accessible from here
            }
        },
        net{
            @Override
            public void setValue(){
                someValue  = "This is a net";  //Some value isn't accessible from here
            }
        };
        public abstract void setValue();
    }
}

然后,像这样:

MyClass myObject = new MyClass();
myObject.setType(ObjectType.ball);

完成上述操作后,myObject 的 'someValue' 字符串现在应该设置为 'This is a ball'。

有什么办法可以做到这一点吗?

嵌套的enum类型是隐式静态的(请参阅 java 枚举变量是静态的吗?)。这包括声明为内部类的enum类型,因此它们无法访问外部类的实例字段。

你不能用enum做你想做的事情,你必须把它建模为一个普通的类。

如果您希望MyClass.someValue等于枚举的someValue,您可以执行以下操作,但是由于可以从枚举中检索someValue,因此我根本不会在MyClass上拥有someValue,只需在需要时从枚举中检索它

public class MyClass {
    ObjectType type;
    String someValue;
    public void setType(ObjectType thisType) {
        this.type = thisType;
        this.someValue = thisType.getSomeValue();
    }
    enum ObjectType {
        ball ("This is a ball"),
        bat ("This is a bat"),
        net ("This is a net");
        private final String someValue;
        ObjectType(String someValue) {
            this.someValue = someValue;
        }
        public String getSomeValue() {
            return someValue;
        }
    }
}

最新更新