enum valueOf IllegalArgumentException: No enum const class

依然范特西╮ 提交于 2021-02-04 13:37:09

问题


I have used enums in java in the past but for some reason I am getting a strange error right now. the Line of code that it is throwing the error is:

switch(ConfigProperties.valueOf(line[0].toLowerCase()){
    ...
}

I am getting a

java.lang.IllegalArgumentException: No enum const class
  allautomator.ConfigProperties.language 

in the example line is an array of Strings.

I am just really confused right now, I do not know what could possibly be wrong.


回答1:


The enum constants are case sensitive, so make sure you're constants are indeed lower case. Also, I would suggest that you trim() the input as well to make sure no leading / trailing white-space sneak in there:

ConfigProperties.valueOf(line[0].toLowerCase().trim())

For reference, here is a working sample program containing your line:

enum ConfigProperties { prop1, prop2 }

class Test {
    public static void main(String[] args) {

        String[] line = { "prop1" };

        switch (ConfigProperties.valueOf(line[0].toLowerCase())) {
        case prop1: System.out.println("Property 1"); break;
        case prop2: System.out.println("Property 2"); break;
        }
    }
}

Output:

Property 1



回答2:


I am using a similar concept, but having a default value in case of fail

public enum SortType {

    PRICE_ASC("price_asc"),
    PRICE_DESC("price_desc"),
    MODEL_ASC("model_asc"),
    MODEL_DESC("model_desc");

    private String name;

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

    public String getName() {
        return name;
    }

    static public SortType lookup(String id, SortType defaultValue) {
        try {
            return SortType.valueOf(id);
        } catch (IllegalArgumentException ex) {
            return defaultValue;
        }
    }
}


来源:https://stackoverflow.com/questions/6062925/enum-valueof-illegalargumentexception-no-enum-const-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!