Java:匿名枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3305237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:13:23  来源:igfitidea点击:

Java: anonymous enums?

java

提问by Ricket

Does Java have the possibility of anonymous enums?

Java 是否有匿名枚举的可能性?

For example, I want my class to have one variable, whose value can be one of 5 different settings. So obviously that variable should be an enum. But this is the ONLY place where that particular enum will be used. Normally I would declare an enum type right above the variable and then declare the variable to be that type, but I was wondering if there is a cleaner way. Does Java support anonymous enums?

例如,我希望我的班级有一个变量,其值可以是 5 种不同设置之一。很明显,该变量应该是一个枚举。但这是使用该特定枚举的唯一地方。通常我会在变量正上方声明一个枚举类型,然后将变量声明为该类型,但我想知道是否有更简洁的方法。Java 是否支持匿名枚举?

Example:

例子:

public class Test {
    public enum Option {
        FirstOption,
        SecondOption,
        ThirdOption
    }
    Option option;
}

Is there a way to avoid declaring public enum Optionand instead simply allow the option variable to be set to either FirstOption, SecondOption or ThirdOption with no notion of the "Option" type?

有没有办法避免声明public enum Option,而只是允许将选项变量设置为 FirstOption、SecondOption 或 ThirdOption 而没有“Option”类型的概念?

回答by cletus

No Java does not support anonymous enums.

没有 Java 不支持匿名enums。

Just declare them inside the class with no external visibility:

只需在没有外部可见性的类中声明它们:

public class Test {
  private static enum Option {
    FirstOption,
    SecondOption,
    ThirdOption
  }

  Option option;
}