I'm refactoring some old code to use enum
's instead of String
constants. I was reviewing my code when I noticed that comparing enum
to String
won't throw an exception. I can't delete the old constants because other projects are still using them.
I can't override the equals because JLS specifically forbids this:
The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.
The code looks like this:
public enum Gender{
MALE,
FEMALE
}
// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";
//following are obviously false
MALE.equals(Gender.MALE)
Gender.MALE.equals(MALE)
For a regular object I could override equals and throw an exception but for my example it will just return false. Also there was a method like getGender that was returning string and now is return an enum so there can be places I missed and a string is compared to enum
This is error-prone. FindBugs is also not reporting any bug. Is there anyway I can protect against this?