0

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?

1 Answer 1

7

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 );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to get the name of the enum value by the string of the constructor?
+1 You could create a static fromString(String s) method that iterates over ServerPackets.values() and returns the matching enum (if found).
Don't forget the enum.valueOf(String) method.
JoshuaBakker - See edit above. Axel's linear approach may also be appropriate. @OldCurmudgeon - that's being used in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.