Joshua Bakker
Joshua Bakker

Reputation: 99

Get enum value from string constructor

In Java, I am trying to get the enum value from a string.

For example I got:

MESSENGERINIT("@L")

This is in the enum as well:

private String header;

private ServerPackets(String header) 
{
    this.header = header;
}

public String getHeader()
{
    return this.header;
    //more code here.
}   

But if I try to use:

System.out.println("[" + ServerPackets.valueOf(header) + 
    "] - Received unregistered header " + 
    Base64Encoding.decode(header) + "(" + header + ") with body " + 
    connection.reader.toString());

I get this error:

java.lang.IllegalArgumentException: No enum constant 
com.kultakala.communication.ServerPackets.@L
    at java.lang.Enum.valueOf(Unknown Source)</code>

What does the error message mean and what I'm doing wrong?

Upvotes: 0

Views: 3300

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86381

Enum.valueof(String) uses the name of the enumerator -- MESSENGERINIT -- not the string you passed to the constructor.

If you want to map other strings to the enumerators, consider creating a static map in the enumerator class.

For example:

enum ServerPackets {
...

private static Map<String,ServerPackets> s_map = new HashMap<String,ServerPackets>();
static {
    map.put( "@L", MESSENGERINIT);
    ...
}
public ServerPackets getEnumFromHeader( String header ) {
   return map.get( header );
}

Upvotes: 7

Related Questions