【问题标题】:Enum to String Conversion枚举到字符串的转换
【发布时间】:2014-03-10 06:50:44
【问题描述】:

我有一个类TestCase。在这里面我有内部类测试。在类枚举 OwnerType 中,带有枚举的 setter 和 getter。

public static final class Test {
    public enum OwnerType {
        User("User"), Role("Role");
        private final String value;
        private OwnerType(String value) {
            this.value = value;
        }
        public String toValue() {
            return value;
        }
    }

    private OwnerType m_ownerType;
    public OwnerType getOwnerType() {
        return m_ownerType;
    }

    public void setOwnerType(OwnerType m_ownerType) {
        this.m_ownerType = m_ownerType;
    }

    private JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        obj.put(KEY, new JSONString(m_ownerType.toString())); // Showing Error Enum to String Conversion

        return obj;
    }
}

m_ownerTypeOwnerType Enum 所以在obj.put() 我做错了一些从枚举到字符串的转换。

谢谢。

【问题讨论】:

  • 您遇到什么错误?变量m_ownerType 声明在哪里?
  • @RohitJain :更新了问题。
  • 那个枚举类甚至不会编译
  • 另外,你遇到了什么错误?
  • @KugathasanAbimaran:已更新。我有一个 OwnerType 的构造函数,它接受一个字符串类型的参数。

标签: java string gwt enums type-conversion


【解决方案1】:

java 枚举带有内置函数name(),这是将它们序列化为字符串的首选方法。

【讨论】:

  • obj.put(KEY, new JSONString(m_ownerType.toString()));代替这个 obj.put(KEY, new JSONString(m_ownerType.name()));你是说..?
  • @user3177233 - 不,我的意思是 put(key, m_ownerType.name());
  • @radai obj 不是map,而是JSONObject
  • @radai :好的,我试过了,但它表明 JSONObject 类型中的 put(String, JSONValue) 方法不适用于参数 (String, String)
  • @user3177233 那么您将如何解决该错误?不要只是盲目地发布您面临的所有问题。尝试调试问题。读出错误信息,想想哪里出了问题。当然你不能将String 传递给参数类型JSONValue。那么,您将如何将 JSONValue 作为参数传递?
【解决方案2】:

看看Three ways to Serialize Java Enums。这取决于您的用例,但在大多数用例中使用 name() 方法看起来不错。

【讨论】:

    【解决方案3】:

    enum 中您真正需要的是:

    public enum OwnerType {
        User,
        Role
    }
    

    要获取它的值作为字符串,您可以调用.name().toString()

    OwnerType ot = OwnerType.User;
    System.out.println("Owner is of type: " + ot.name());
    

    这将打印出“所有者的类型:用户”。接下来的两个将产生相同的结果:

    System.out.println("Owner is of type: " + ot.toString());
    System.out.println("Owner is of type: " + ot); // Implicit call to toString()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多