java.lang.IllegalArgumentException的原因是什么:没有枚举const类,即使迭代值()工作正常吗? [英] What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

查看:7608
本文介绍了java.lang.IllegalArgumentException的原因是什么:没有枚举const类,即使迭代值()工作正常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题基本上是我的上一个问题的扩展。我问前一个问题,以确保在类加载时填充枚举常数。这是我的课程,再次添加了一个简单的方法 getByName

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);
  }
}

调用方法 getByName(columnHeadings)正在抛出 java.lang.IllegalArgumentException:否枚举const class labware.web.component.limsgrid.PropName.columnHeadings but如果我用以下代码替换这个方法,它只是工作。

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 ?

推荐答案

Enum.valueOf()只检查常量名称,所以你需要传递COLUMN_HEADINGS而不是columnHeadings。您的名称属性与Enum内部结构无关。

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.

这篇关于java.lang.IllegalArgumentException的原因是什么:没有枚举const类,即使迭代值()工作正常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆