【问题标题】:Accessing superclass variables from an enum从枚举访问超类变量
【发布时间】:2015-03-16 20:57:38
【问题描述】:

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

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”。

有什么办法吗?

【问题讨论】:

  • 将状态存储在枚举中,或者通过使其看起来可变来获得这种能力,是一个非常糟糕的主意。但是,您可以做的是在枚举的构造函数中传递参数。看看Planet example

标签: java object enums enumeration


【解决方案1】:

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

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

【讨论】:

  • “所以他们不能访问外部类的成员字段”如果我没记错的话他们可以,但是他们需要外部类的显式实例,比如public void setValue(MyClass mc){ mc.someValue = "This is a ball";}
  • 你不能设置外部类的字段是对的,但通过 enum ObjectType extends MyClass 解决了这个问题。
  • @SotiriosDelimanolis 你可能是对的,但它绝对可以implement 某事。
  • @skaffman 我在对这个问题的评论中说,这可能是一个错误的问题。这是对枚举的滥用或有效使用,但最好使用参数化枚举构造函数。
【解决方案2】:

如果您希望 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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-09
    • 2022-01-12
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多