Java – how to detect that a new value has been added to the enumeration and is not processed in the switch

From time to time, I want to add a new value to the enumeration type of the project

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

What I want is that every switch I don't process new values has a compile time error, as shown below:

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

There is a default: throwing some exceptions is not good enough. I hope it is compile time

I don't think it's possible, but maybe someone has a clever trick

I think findbugs has rules to find those, but I only see this: EQ: covariant equals() method defined for ENUM (eq_don_define_equals_for enum)

Editor: I chose Mark's reply. I did use eclipse. It sounded like what I needed! I'm not an expert at findbugs at all, so I may have missed this feature, although I don't think so

Solution

Eclipse has a compile time warning / error that can be enabled: "switch" does not contain enumeration constants

From project properties (or general preferences), go to Java compiler - > errors / warnings, and select enable project specific settings You will find warnings under potential programming problems It is set to ignore by default, but you can promote it to warning or error

Editor: I think it's self-evident, but I think I'll say: this only applies if you develop or use it for build management in eclipse Obviously, findbugs or similar equivalent will be the "real" answer because it goes beyond the IDE and can be integrated into the construction process

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>