如何检测新值已添加到枚举中并且未在 switch 中处理

发布于 2024-09-28 08:57:00 字数 1089 浏览 2 评论 0原文

有时我必须向项目中的枚举类型添加新值。

public enum Day {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, 
   FILENOTFOUND //this one is new one
}

我想要的是对于我拥有的每个不处理新值的开关都有一个编译时错误,就像这样:

switch (color) {
        case MONDAY: 
        case TUESDAY: 
        case WEDNESDAY: 
        case THURSDAY: 
                    System.out.println("Mondays are bad.");
                     break;

        case FRIDAY: System.out.println("Fridays are better.");
                     break;

        case SATURDAY:
        case SUNDAY: System.out.println("Weekends are best.");
                     break;
    } 

有一个默认值:抛出一些异常还不够好,我会喜欢它是编译时间。

我不认为这是可能的,但也许有人有一个巧妙的技巧...

我以为 Findbugs 会有一个规则来找到这些,但我只看到了这个: Eq:为枚举定义的协变 equals() 方法 (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)

编辑:< /strong> 我选择 Mark 的回复,我确实使用 Eclipse,这听起来正是我所需要的!我根本不是 findbugs 方面的专家,所以我可能错过了这样的功能,尽管我不这么认为。

From time to time I have to add a new value to a enum type in my project.

public enum Day {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, 
   FILENOTFOUND //this one is new one
}

What I would like is to have a compile time error for every switch I have that is not treating the new value, like this one:

switch (color) {
        case MONDAY: 
        case TUESDAY: 
        case WEDNESDAY: 
        case THURSDAY: 
                    System.out.println("Mondays are bad.");
                     break;

        case FRIDAY: System.out.println("Fridays are better.");
                     break;

        case SATURDAY:
        case SUNDAY: System.out.println("Weekends are best.");
                     break;
    } 

Having a default: that throws some exception is not good enough, I would like it to be compile time.

I don't think this is possible but maybe someone has a neat trick...

I thought Findbugs would have a rule to find those but I only saw this:
Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)

EDIT: I'm choosing Mark's reply, I do use Eclipse and that sounds just like what I needed! I am not an expert in findbugs at all so I might have missed such functionality, though I don't think so.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梅窗月明清似水 2024-10-05 08:57:00

Eclipse 有一个编译时警告/错误,您可以启用:“switch”上未涵盖枚举常量。

从您的项目属性(或常规首选项),转到Java 编译器 ->错误/警告,选中启用项目特定设置。您将在潜在编程问题下找到该警告。默认情况下,它设置为忽略,但您可以将其提高为警告错误

编辑: 我认为这是不言而喻的,但我想我还是要说一下:这仅适用于您在 Eclipse 中进行开发或将其用于构建管理的情况。显然,Findbugs 或类似的等效工具将是“真正的”答案,因为它超越了 IDE 并且可以集成到构建过程中。

Eclipse has a compile-time warning/error you can enable: Enum constant not covered on "switch".

From your Project properties (or general preferences), go to Java Compiler->Errors/Warnings , check Enable project specific settings. You'll find the warning under Potential programming problems. It's set to Ignore by default but you can bump it up to Warning or Error.

Edit: I thought this goes without saying but I suppose I'll say it anyway: this is only applicable if you're developing in Eclipse or using it for your build management. Obviously a Findbugs or similar equivalent would be the "real" answer since it transcends the IDE and can be integrated into the build process.

罪歌 2024-10-05 08:57:00

您可以通过添加默认子句并在访问时进行记录来做到这一点:(

switch (color) {
default:
    log.error("Unknown color in switch: " + color);
    break

case MONDAY: /*FALLTHROUGH*/
case TUESDAY: 

添加失败注释可以帮助后来的维护者决定您是否忘记了代码:-))

编辑从马克答案的评论中复制的澄清:

像这样的 IDE 功能信号情况对于开发人员来说在更改时很好,但它不会捕获代码所依赖的代码其他部分的更改。

它不会使包含枚举开关的古代代码对更改具有鲁棒性,除非针对新版本重新编译它们。

当客户端代码记录未处理的情况时,它确实有帮助;部署的代码并不总是能够完全控制其类路径或其上的库的版本。

You could do that by adding a default clause and logging when it is visited:

switch (color) {
default:
    log.error("Unknown color in switch: " + color);
    break

case MONDAY: /*FALLTHROUGH*/
case TUESDAY: 

(adding fallthrough comments help later maintainers to decide whether you forgot code or not :-))

Edit Clarification copied from comments on Mark's answer:

An IDE feature signalling cases like this is fine for the developer at the moment of the change but it does not catch changes in other parts of code that your code depends on.

It does not make the cient code containing switches on enums robust against changes unless they are recompiled against the new version.

It does help when the client code logs unhandled cases; deployed code does not always have full control over its classpath or the versions of libraries on it.

谁许谁一生繁华 2024-10-05 08:57:00

IntelliJ 是一项检查,其中未设置所有情况。它有一个自动修复功能来填补缺失的情况。

IntelliJ was a check where not all case have been set. It has an auto-fix to fill in the missing cases.

野却迷人 2024-10-05 08:57:00

自 Java 14(带有 JEP 361)以来,现在有了 Switch Expressions,它可以让你就这么做。对于您的示例,这将如下所示:

String feeling = switch (day) {
    case MONDAY => "Mondays are bad.";
    case TUESDAY => "Tuesdays are bad.";
    case WEDNESDAY => "Wednesdays are bad.";
    case THURSDAY => "Thursdays are bad.";
    case FRIDAY => "Fridays are better.";
    case SATURDAY => "Weekends are best.";
    case SUNDAY => "Weekends are best."
}
System.out.println(feeling);

如果您添加新的枚举值 FILENOTFOUND 那么您会收到编译错误:java:switch 表达式未涵盖所有可能的输入值

Since Java 14 (with JEP 361) there are now Switch Expressions which lets you do that. For your example this would then look like that:

String feeling = switch (day) {
    case MONDAY => "Mondays are bad.";
    case TUESDAY => "Tuesdays are bad.";
    case WEDNESDAY => "Wednesdays are bad.";
    case THURSDAY => "Thursdays are bad.";
    case FRIDAY => "Fridays are better.";
    case SATURDAY => "Weekends are best.";
    case SUNDAY => "Weekends are best."
}
System.out.println(feeling);

If you add a new enum value FILENOTFOUND then you get a compile error: java: the switch expression does not cover all possible input values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文