【问题标题】:String Value to set an Enum设置枚举的字符串值
【发布时间】:2011-05-30 21:55:31
【问题描述】:

我想通过使用枚举类型之一作为输入来设置枚举类型:

这是我正在使用的代码,

    package models;

    import models.crudsiena.SienaSupport;
    import siena.*;

    public class Item extends SienaSupport {

        @Id
        public Long id;


           public static enum Type{
              A,
              B
            };

            public Type itemType;

            public Item(String itemType) {
               this.itemType = Type.valueOf(itemType);
            }
}

当我尝试使用 new Item("A") 时,它会返回一个 NullPointerException occured : Name is null

【问题讨论】:

  • 我无法重现这个。请展示一个简短但完整的程序来演示问题。
  • 正如乔恩所说,问题一定出在其他地方,您发布的代码应该可以正常工作。
  • 您好,感谢您抽出宝贵的时间,我将在一秒钟内添加更多内容,对此感到抱歉。这是堆栈跟踪:pastebin.com/xBjBm4pM

标签: java enums model value-of


【解决方案1】:

试试这个:

public Item(String itemType) {
   if (itemType == null) {
       throw new IllegalArgumentException("null itemType");
   }
   this.itemType = Type.valueOf(itemType);
}

【讨论】:

  • 我刚试过,它返回了 null itemType 异常,所以我的输入一定有问题
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多