如何在编译时确保枚举开关的完整性? [英] How to ensure completeness in an enum switch at compile time?

查看:119
本文介绍了如何在编译时确保枚举开关的完整性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个switch语句测试枚举。必须通过案例开关语句中处理所有枚举值c>声明。在代码重构期间,可能会发生枚举收缩和增长。当枚举缩小时,编译器会抛出错误。但是,如果枚举增长,则不会抛出任何错误。匹配状态被遗忘并产生运行时错误。我想将此错误从运行时移动到编译时。从理论上讲,应该可以在编译时检测丢失的枚举个案。有没有办法实现这个目标?

I have several switch statements which test an enum. All enum values must be handled in the switch statements by a case statement. During code refactoring it can happen that the enum shrinks and grows. When the enum shrinks the compiler throws an error. But no error is thrown, if the the enum grows. The matching state gets forgotten and produces a run time error. I would like to move this error from run time to compile time. Theoretically it should be possible to detect the missing enum cases at compile time. Is there any way to achieve this?

问题已经存在如何检测新值被添加到枚举中而不是在交换机中处理但它不包含仅与Eclipse相关的解决方案的答案。

The question exists already "How to detect a new value was added to an enum and is not handled in a switch" but it does not contain an answer only an Eclipse related work around.

推荐答案

另一个解决方案使用功能方法。你只需要根据下一个模板声明枚举类:

Another solution uses the functional approach. You just need to declare the enum class according with next template:

public enum Direction {

    UNKNOWN,
    FORWARD,
    BACKWARD;

    public interface SwitchResult {
        public void UNKNOWN();
        public void FORWARD();
        public void BACKWARD();
    }

    public void switchValue(SwitchResult result) {
        switch (this) {
            case UNKNOWN:
                result.UNKNOWN();
                break;
            case FORWARD:
                result.FORWARD();
                break;
            case BACKWARD:
                result.BACKWARD();
                break;
        }
    }
}

如果你试图用这个如果没有一个枚举常量,你将得到编译错误:

If you try to use this without one enumeration constant at least, you will get the compilation error:

getDirection().switchValue(new Direction.SwitchResult() {
    public void UNKNOWN() { /* */ }
    public void FORWARD() { /* */ }
    // public void BACKWARD() { /* */ } // <- Compilation error if missing
});

这篇关于如何在编译时确保枚举开关的完整性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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