Java – enum: have I just done something I don’t need?
I have an enumeration class. It has several constants. I want to add some static values focused to indicate which enumeration value has focus
I found a way:
package messagesystem; /** * * @author Frank */ public enum MessageType { ALL,GENERAL,SEND,RECEIVE,LOG,EXCEPTION,DEBUG,PM; public final static MessageType FOCUSED = GENERAL; private final String value; MessageType() { String firstLetter = name().substring(0,1); String otherLetters = name().substring(1,name().length()); this.value = firstLetter.toUpperCase() + otherLetters.toLowerCase(); } @Override public String toString() { return value; } }
But now I want to know: am I just messing up enumeration classes? Because I don't want to select focused when specifying the message type, but the class handling the MessageType enumeration should be able to determine the focused value... So I don't need to harden it in each class
Any idea is appreciated
Editor: Although the behavior is normal This code provides the expected output:
this.focused = MessageType.FOCUSED.toString(); System.out.println(focused);
The output is general
Solution
Focused is just an alias of general It will not appear in the enumerated value (). If some client code uses focused, it will actually use general, because both variables refer to the same enumerated value So no, I don't think you screwed up
To reduce confusion, perhaps you should make focused () a static method that returns general If you determine that the focus type is another type, this also avoids the need to recompile the client code