java - 处理来自在开关/案例中实现特定接口(interface)的不同枚举的枚举值

标签 java enums switch-statement

我有一个空接口(interface) Units,我用它来标记不同的 enums,所以我知道它们有不同的单位(例如,我有一个 enum TemperatureUnits实现存储华氏度、摄氏度等的单位{},然后我有一个包含米、英尺等的 DistanceUnits

我想根据传递给方法的 enum 值在 switch/case 中做不同的事情。我希望它接受来自实现 Units 的任何 enum 的值。问题是,由于 enums 实际上是不同的类,我必须在 switch/case 中使用值的限定名称。我的代码看起来像这样:

     public static void foo(Units units){ //units has to be an enum that implements Units

        switch (units){
            case TemperatureUnits.FAHRENHEIT: //I can't say just FAHRENHEIT, because Units itself doesn't 
                //have a FAHRENHEIT value, but it won't let me say TemperatureUnits.FAHRENHEIT because it won't let use
                // qualified enum values as cases.
                //Do stuff
                break;
            case DistanceUnits.METERS:
                //Do other stuff
                break;
            //...etc

我如何拥有一个可以使用来自不同enums 的值的 switch/case 语句?

编辑:我的 Units 界面只是:

public interface Units{
    String getLabel();
}

最佳答案

Java 语言规范不允许这样做。

14.11. The switch Statement

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

此处,表达式 是您要打开的值 (switch(expression))。在您的例子中,表达式的类型是 Units,它是一个接口(interface)而不是 enum

旁边

Every case label has a case constant, which is either a constant expression or the name of an enum constant.

Enum constants不符合枚举类型,因此您不能在一个开关中混合使用不同的枚举类型常量。

一个可能的解决方案是像这样实现它:

interface Unit {
    void doSomething();
}

enum A implements Unit {
    A_ONE,
    A_TWO,
    A_THREE {
       void doSomething() {
           // implement it in a way specific for A_THREE
       }
    };

   void doSomething() {
       // implement it in a generic way for A
   }
}

这样,每个实现 Unit 的枚举都可以——而且必须——将“处理逻辑”封装在其中,如果你有任何特殊的枚举常量——它们可以自己实现特殊逻辑。自然地,有时每个枚举常量都可以有一个特定的实现,并且在枚举类级别上不会有一个泛型。

关于java - 处理来自在开关/案例中实现特定接口(interface)的不同枚举的枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34482243/

相关文章:

java.lang.IllegalStateException : Neither BindingResult nor plain target object for bean name 'subscription' available as request attribute

java - 在 Android 应用程序中发送电子邮件

C#:非法 Switch 语句的解决方法?

nhibernate - Hibernate/NHibernate 中的枚举表

Angular 2 [ngSwitchCase] 不支持负值?

swift - 为什么我不能在 switch 语句中使用元组常量作为 case

java - 视力 jSTL c :set analog

java - 如何让一个声音在Processing中播放一次?

android - 带有字符串的枚举或密封类

java - 如何在 Android 中创建多语言枚举?