为什么在此代码中的枚举上的切换需要默认值? [英] Why is default required for a switch on an enum in this code?

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

问题描述

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

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";
    }
}


推荐答案

您必须取消注释默认值的原因是您的函数表示它返回一个 String ,但如果您只有 case A B 定义的标签,则该函数将如果您传递任何其他内容,则不返回值。 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.

我相信(我不知道这一点),原因是即使你涵盖了所有的枚举案例,代码可能在某些情况下仍然失败。特别是,假设您编译包含此switch语句的Java代码(可以正常工作),然后更改枚举,以便现在有第三个常量 - 让我们说 C - 但是您不会使用开关语句重新编译代码。现在,如果您尝试编写使用先前编译的类并且将 C 传入此语句的Java代码,则代码将不会返回值,从而违反所有函数总是返回值的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天全站免登陆