如何检测新值已添加到枚举,并且不在交换机中处理 [英] How to detect a new value was added to an enum and is not handled in a switch

查看:159
本文介绍了如何检测新值已添加到枚举,并且不在交换机中处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不时地向我的项目中的枚举类型添加一个新值。

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
}

我想要的是有一个编译时错误每个开关,我有没有处理新的值,像这样: / p>

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...

我认为Findbugs会有一个规则找到那些,但我只看到了:
Eq:为枚举定义的Covariant equals()方法(EQ_DONT_DEFINE_EQUALS_FOR_ENUM)

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)

编辑:我选择Mark的回复做使用Eclipse,听起来就像我所需要的!我不是在findbugs的专家,所以我可能会错过这样的功能,虽然我不这么认为。

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.

推荐答案

Eclipse具有可启用的编译时警告/错误:switch未涵盖的枚举常量。

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

在您的专案属性(或一般偏好设定)中,前往 Java Compiler - > 错误/警告,请选中启用项目特定设置。您会在潜在的编程问题下找到警告。默认情况下,它设置为忽略,但您可以将其展开为警告错误

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.

编辑:我认为这是不必说的,但我想我会说它无论如何:这只适用于如果你在Eclipse中开发或使用它进行你的构建管理。显然,Findbugs或类似的等价物将是真正的答案,因为它超越了IDE,可以集成到构建过程中。

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.

这篇关于如何检测新值已添加到枚举,并且不在交换机中处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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