Tuesday, December 21, 2004

Type Safe Enums

Overloading int considered harmful: part "On the other hand, enums do not handle multi-classloader issues automatically. It is absolutely possible to have FontStyle.PLAIN != FontStyle.PLAIN when the FontStyle class is loaded twice by two different class loaders. If this is a real possibility in your code (and if you're writing a library, it's always a real possibility), the obvious solution is to override equals with a method that does work. Unfortunately, you can't do that. The equals method in java.lang.Enum is declared final, and all it does is compare objects for object identity with ==. So you really have no choice but to buckle down, write your own type-safe enum class, and warn client programmers to always use equals instead of == when comparing objects."

No comments: