为了账号安全,请及时绑定邮箱和手机立即绑定

在Java中开启Enum

在Java中开启Enum

温温酱 2019-11-14 09:39:00
为什么不能打开Java枚举?看起来很简单,可以编写一些方便的代码。这个问题也适用于String。您可以打开char,但不能打开String...?
查看完整描述

3 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

实际上,您可以switch使用enums,但是直到Java 7才可以switch使用Strings。您可以考虑将Java enum的多态方法分派使用,而不是显式switch。请注意,enums是Java中的对象,而不仅仅是ints的符号,就像在C / C ++中一样。您可以在enum类型上有一个方法,然后不用编写a switch,只需调用该方法-一行代码即可:完成!


enum MyEnum {

    SOME_ENUM_CONSTANT {

        @Override

        public void method() {

            System.out.println("first enum constant behavior!");

        }

    },

    ANOTHER_ENUM_CONSTANT {

        @Override

        public void method() {

            System.out.println("second enum constant behavior!");

        }

    }; // note the semi-colon after the final constant, not just a comma!

    public abstract void method(); // could also be in an interface that MyEnum implements

}


void aMethodSomewhere(final MyEnum e) {

    doSomeStuff();

    e.method(); // here is where the switch would be, now it's one line of code!

    doSomeOtherStuff();

}


查看完整回答
反对 回复 2019-11-14
  • 3 回答
  • 0 关注
  • 359 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信