Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum: Did I just do something unwanted?

Tags:

java

enums

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".

like image 883
skiwi Avatar asked Oct 21 '22 10:10

skiwi


1 Answers

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.

like image 91
JB Nizet Avatar answered Oct 30 '22 23:10

JB Nizet