I have an enum class which has several constants, and I want to add some static value FOCUSED
which indicates which of the enum values 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;
}
}
However, now I wonder: Did I just mess with the enum class? Because I don't want FOCUSED
to be selectable when specifying the message type, however a class handling an enum of MessageType
should be able to determine the FOCUSED
value... Such that I do not need to hardcore it in every class.
Any thoughts are appreciated.
EDIT: It is behaving correctly though. This code gives the expected output:
this.focused = MessageType.FOCUSED.toString();
System.out.println(focused);
The output is "General".
FOCUSED is just an alias to GENERAL. It won't appear in the values()
of the enum, and if some client code uses FOCUSED, it will in fact use GENERAL, as both variables refer to the same enum value. So no, I don't think you messed up.
To reduce the confusion, maybe you should make focused()
a static method, which returns GENERAL. This would also avoid the need to recompile client code in case you decide that the focused type is another one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With