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

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

问题描述

通常,switch 语句中不需要 default.但是,在以下情况下,只有当我取消注释 default 语句时,代码才能成功编译.谁能解释一下为什么?

Normally, default is not necessary in a switch statement. However, in the following situation the code successfully compiles only when I uncomment the default statement. Can anybody explain why?

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

推荐答案

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

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.

我相信(并且我不确定这一点)的原因是,即使您涵盖了所有 enum 情况,代码在某些情况下仍然可能会失败.特别地,假设您编译包含此 switch 语句的 Java 代码(工作正常),然后稍后更改 enum 以便现在有第三个常量 - 比方说 C - 但您不会使用 switch 语句重新编译代码.现在,如果您尝试编写使用先前编译的类并将 C 传递到此语句中的 Java 代码,那么该代码将没有要返回的值,这违反了所有函数总是返回值.

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.

从技术上讲,我认为真正的原因是 JVM 字节码验证器总是拒绝在函数末尾有一些控制路径的函数(参见 §4.9.2 JVM 规范的),所以如果代码要编译它就会被拒绝无论如何,在运行时由 JVM 执行.因此,编译器会给出错误报告,报告存在问题.

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天全站免登陆