Geek Geek - 3 months ago 8
Java Question

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

This question is basically an extension of my previous question . I asked the previous question to be sure that the Enum constants are populated when the class loads . Here's is my class again with the addition of a simple method

getByName
:

public enum PropName {

CONTENTS("contents"),
USE_QUOTES("useQuotes"),
ONKEYDOWN("onkeydown"),
BROWSER_ENTIRE_TABLE("browseEntireTable"),
COLUMN_HEADINGS("columnHeadings"),
PAGE_SIZE("pageSize"),
POPUP_TITLE("popupTitle"),
FILTER_COL("filterCol"),
SQL_SELECT("sqlSelect"),
;

private String name;

private PropName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public static PropName getByName(String name){
return PropName.valueOf(name);
}
}


A call to the method
getByName("columnHeadings")
is throwing
java.lang.IllegalArgumentException: No enum const class labware.web.component.limsgrid.PropName.columnHeadings
but if I replace this method with the following code it just works .

public static PropName getByName(String name){
for(PropName prop : values()){
if(prop.getName().equals(name)){
return prop;
}
}

throw new IllegalArgumentException(name + " is not a valid PropName");
}


Any ideas as to what I am doing wrong here ?

Answer

Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has nothing to do with Enum internals.