Java 从枚举访问超类变量

Java 从枚举访问超类变量,java,object,enums,enumeration,Java,Object,Enums,Enumeration,有没有办法从枚举本身设置枚举父类/超类中保存的变量?(下面没有编译,但说明了我试图实现的目标) 然后,像这样: MyClass myObject = new MyClass(); myObject.setType(ObjectType.ball); 完成上述操作后,myObject的“someValue”字符串现在应设置为“This is a ball” 有什么方法可以做到这一点吗?嵌套的enum类型是隐式静态的(请参阅)。这包括声明为内部类的enum类型,因此它们无法访问外部类的实例字段 你

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

然后,像这样:

MyClass myObject = new MyClass();
myObject.setType(ObjectType.ball);
完成上述操作后,myObject的“someValue”字符串现在应设置为“This is a ball”


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

嵌套的
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;
        }
    }
}

将状态存储在枚举中,或者通过使其看起来是可变的来拥有这种能力,这是一个非常糟糕的主意。不过,您可以做的是在枚举的构造函数中传递参数。看看“所以他们不能访问外部类的成员字段”,如果我没记错的话,他们可以,但是他们需要外部类的显式实例,比如
public void setValue(MyClass mc){mc.someValue=“This is a ball”;}
。你不能设置外部类的字段,这是对的,但是,通过执行
enum ObjectType extensed MyClass
@SotiriosDelimanolis,这是可以解决的。你可能是对的,但它肯定可以
实现
一些东西。@skaffman我在对问题的评论中说,这可能是一个错误的问题。这是对枚举的滥用或有效使用,但最好使用参数化枚举构造函数。
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;
        }
    }
}