枚举详尽switch语句的静态分析 [英] Static analysis of exhaustive switch statements of enums

查看:36
本文介绍了枚举详尽switch语句的静态分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

enum MyEnum {
  A, B, C;
}

int foo(MyEnum e) {
  switch (e) {
    case A:
      return 1;
    case B:
      return 2;
    case C:
      return 3;
  }
}
^ error: missing return statement

编译器不喜欢这样.将此示例与以下示例进行对比:

The compiler does not like this. Contrast this example with:

int bar() {
  if (...) {
    return 1;
  } else {
    return 2;
  }
}

开关的问题可以通过 default 案例来解决,但您可能会认为这里不需要.所有枚举值都包含在开关的情况下.switch 语句的静态分析是否知道,在穷举 switch 中返回,switch 语句之后的代码块是不可达的?

The issue with the switch could be addressed with a default case, but you could argue that's unneeded here. All of the enum values are covered in the cases of the switch. Does static analysis of the switch statement know that, with returns in an exhaustive switch, the code block after the switch statement is unreachable?

我尝试查看 语言规范,但我没有看到明确解决这一点.

I tried looking at the language spec, but I didn't see this point clearly addressed.

推荐答案

好吧,Java 不像其他语言(如 C/C++ 或 .NET)那样在本地实现枚举.它们只是(最终)类的实例.因此,实际上您的运算符 == 比较的是 引用相等性,而不是您可能建议的整数值.

Well, Java does not implement enums natively as other languages like C/C++ or .NET. They are just instances of a (final) class. So in fact your operator == compares for reference equality rather than integer values as you might have suggested.

这就是switch语句不完整的原因.引用可能只是 null.

This is the reason, why the switch statement is not complete. The reference might just be null.

此外,您可能已经使用公共构造函数定义了自己的枚举类,该构造函数可能会创建任意数量的实例.

Furthermore you might have defined your own enum class with a public constructor which might create any arbitrary number of instances.

顺便说一句:实现你的 foo 方法的最简单的方法是

By the way: the by far easiest way to implement your foo method is

int foo(MyEnum e)
{ return e.ordinal() + 1;
}

但请注意 .ordinal() 不会返回与您的枚举常量相关的任何值.它只是按定义顺序排列的索引.

But note that .ordinal() does not return any value associated with your enum constant. It is just the index in order of definition.

这篇关于枚举详尽switch语句的静态分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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