eliocs
eliocs

Reputation: 18827

Convert a String to an Enum?

Hi I'm having trouble trying to generalize a function I've written for an specific enum:

public static enum InstrumentType {
    SPOT {
        public String toString() {
            return "MKP";
        }
    },
    VOLATILITY {
        public String toString() {
            return "VOL";
        }
    };

    public static InstrumentType parseXML(String value) {
        InstrumentType ret = InstrumentType.SPOT;

        for(InstrumentType instrumentType : values()) {
            if(instrumentType.toString().equalsIgnoreCase(value)) {
                ret = instrumentType;
                break;
            }
        }

        return ret;
    }
} 

I wish to add a new parameter to the function that will represent any enum. I know I'm supposed to use templates but I can't use the function "values()" then inside the function code. Basicly what I want is a valueOf function that uses the toString() value I've defined.

Thanks in advance.

Upvotes: 0

Views: 1839

Answers (2)

Yuval Adam
Yuval Adam

Reputation: 165192

Try a much cleaner way of writing your enum:

public static enum InstrumentType {

    SPOT("MKP"),
    VOLATILITY("VOL");

    private final String name;

    InstrumentType(String name)
    {
        this.name = name;
    }

    public String toString()
    {
        return this.name;
    }

    public static InstrumentType getValue(String s)
    {
        for (InstrumentType t : InstrumentType.values())
        {
            if (t.toString().equals(s))
                return t;
        }
        return SOME_DEFAULT_VALUE;
    }
}

This also solves your problem of String -> Enum. It might be cleaner to just use the three-letter acronyms as the enum name, but in the case you will need to make the getValue() decision according to other parameters, this is the right way to go.

Upvotes: 16

user7094
user7094

Reputation:

I believe that Enums can implement interfaces, so you could define one with a values() method and then use that as your parameter type.

But as the commenter said, it would probably be easier if you named your enums MKP, VOL etc

Upvotes: 0

Related Questions