Java语言中不同枚举类的联合开关语句 [英] switch statement for a joint of different enum classes in Java

查看:90
本文介绍了Java语言中不同枚举类的联合开关语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个枚举类,说Enum1和Enum2:

enum Enum1 {ONE, TWO, THREE}
enum Enum2 {FOUR, FIVE}

一个这样的方法:

public <E extends Enum<E>> method (E arg) {
    switch (arg) {    // Here is the compile error -- Cannot switch
                      // on a value of type E. Only convertible int
                      // values, strings or enum variables are permitted

                      // (And of course, all the cases are incorrect
                      // because the enum set is unknown)
        case ONE:
            // do something
        case TWO:
            // do something
        case THREE:
            // do something
        case FOUR:
            // do something
        case FIVE:
            // do something
        default:
            // do something
    }
}






是否可以切换通用枚举类型的值?






有一种方法可以将其更改为字符串(仅适用于JDK7):


So is it possible to switch a value of a generic enum type?


There is one way to change it to strings (only works in JDK7):

public <E extends Enum<E>> method (E arg) {
    switch (arg.name()) {
        case "ONE":
            // do something
        case "TWO":
            // do something
        case "THREE":
            // do something
        case "FOUR":
            // do something
        case "FIVE":
            // do something
        default:
            // do something
    }
}


推荐答案

你不能做你正在尝试的事情。首先,一个枚举切换实际上是枚举的 ordinal()上的开关的缩写。所以即使你可以得到切换来识别你的联合枚举类型,该语句也有重复的 case 分支。 (例如, ONE FOUR 都有序号0。)

You cannot do what you are trying. For one thing, an enum switch is actually a shorthand for a switch on the ordinal() of the enum. So even if you could get the switch to recognize your "joint enum" type, the statement has duplicate case branches. (For instance, ONE and FOUR both have ordinal 0.)

一种方法可能是将操作移动到枚举本身。然后,您可以将每个枚举类型实现一个通用接口:

One approach might be to move the action into the enums themselves. You can then have each enum type implement a common interface:

interface Actor {
    void doSomething();
}

enum Enum1 implements Actor {
    ONE {
        public void doSomething() { . . . }
    },
    TWO {
        public void doSomething() { . . . }
    },
    THREE {
        public void doSomething() { . . . }
    }
}

enum Enum2 implements Actor {
    FOUR {
        public void doSomething() { . . . }
    },
    FIVE {
        public void doSomething() { . . . }
    }
}

然后你可以实现你的方法来简单地委托处理到演员:

Then you could implement your method to simply delegate the processing to the actor:

public void method(Actor actor) {
    if (actor == null) {
         // default action
    } else {
        actor.doSomething();
    }
}

这篇关于Java语言中不同枚举类的联合开关语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆