Phoenix
Phoenix

Reputation: 8923

Working with Java enums

I want 2 uses out of this enum, first of all at some point these int values will be coming out of the database. Without modifying the constructor, I would like to get a user friendly name out of it, as in if an object contains INS, I want one of the methods on the enum to return "Insurance" .. How do I add such methods to this enum (without modifying the constructor), that would give the programmer the technical name, such as "HCARE" and user the user friendly name "Insurance". Also, would like to know what changes would I need to make in getting the user friendly name from the database ?

public enum Type
{
    UNDEF(-1),
    HCARE(1),
    INS(2);

    private int value;

    Type(final int value)
    {
        this.value = value;
    }

}

Upvotes: 0

Views: 85

Answers (2)

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

Override toString for each member:

public enum Type
{
    UNDEF(-1)
    {
         public String toString(){ return "Friendly name here"; }
    },
    HCARE(1)
    {
         public String toString(){ return "Friendly name here"; }
    },
    INS(2)
    {
         public String toString(){ return "Insurance"; }
    };

    private int value;

    Type(final int value)
    {
        this.value = value;
    }

    public abstract String toString();

}

The documentation says that "An enum type should override [toString] when a more "programmer-friendly" string form exists."

Upvotes: 1

Thilo
Thilo

Reputation: 262474

You can add a method to get the user-friendly name out of the database (probably caching it) or from somewhere else initially (such as a resource file).

Since we are talking display names here, I also added a Locale parameter, so it can support multiple languages.

public enum Type
{
    UNDEF(-1),
    HCARE(1),
    INS(2);

    private int value;

    Type(final int value)
    {
        this.value = value;
    }

    public String getNiceName(Locale l){
        // look at my id and code and use that to look up the name
        return NiceNameManager.nameForType(this, l);
    }
}

Upvotes: 1

Related Questions