为什么打开枚举需要默认值? [英] Why is default required for a switch on an enum?

查看:107
本文介绍了为什么打开枚举需要默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在switch语句中不需要默认值.但是,在以下情况下,仅当我取消注释默认语句时,代码才能成功编译.有人可以解释为什么吗?

public enum XYZ {A,B};
public static String testSwitch(XYZ xyz)
{
    switch(xyz)
    {
    case A:
        return "A";
    case B:
    //default:
        return "B";
    }
}

解决方案

您必须取消注释default的原因是您的函数说它返回了String,但是如果您只有case标签为AB定义,则如果您传入其他任何内容,该函数将不会返回值. Java要求所有声明它们返回值的函数实际上在所有可能的控制路径上都返回一个值,并且在您的情况下,编译器不确信所有可能的输入都返回了值.

我相信(我不确定),原因是即使您涵盖了所有enum情况,代码在某些情况下仍然可能失败.特别是,假设您编译包含此switch语句的Java代码(效果很好),然后更改enum,以便现在有了第三个常量-假设C-但您无需重新编译其中包含switch语句的代码.现在,如果您尝试编写使用先前编译的类并将C传递到此语句中的Java代码,则该代码将没有返回值,这违反了Java协定,即所有功能始终返回值.

从技术上讲,我认为真正的原因是JVM字节码验证程序始终拒绝其中某些控制路径不在函数末尾的函数(请参见§ 4.9.2

The reason that you have to uncomment the default is that your function says that it returns a String, but if you only have case labels defined for A and B then the function will not return a value if you pass in anything else. Java requires that all functions that state that they return a value actually return a value on all possible control paths, and in your case the compiler isn't convinced that all possible inputs have a value returned.

I believe (and I'm not sure of this) that the reason for this is that even if you cover all your enum cases, the code could still fail in some cases. In particular, suppose that you compile the Java code containing this switch statement (which works just fine), then later on change the enum so that there's now a third constant - let's say C - but you don't recompile the code with the switch statement in it. Now, if you try writing Java code that uses the previously-compiled class and passes in C into this statement, then the code won't have a value to return, violating the Java contract that all functions always return values.

More technically speaking, I think the real reason is that the JVM bytecode verifier always rejects functions in which there is some control path that falls off the end of a function (see §4.9.2 of the JVM spec), and so if the code were to compile it would just get rejected by the JVM at runtime anyway. The compiler therefore gives you the error to report that a problem exists.

这篇关于为什么打开枚举需要默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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