Grails 如何将字符串转换为枚举?

发布于 2025-01-08 08:39:19 字数 557 浏览 3 评论 0原文

我的枚举中有一个自定义 toString 方法:

enum TaxRate implements Serializable {
    RATE23(23.0),
    ...

    private String s
    private BigDecimal rate

    private TaxRate(BigDecimal s) {
        this.s = s + "%"
        this.rate = s * 0.01
    }

    public String toString() {
        return s
    }

现在,当我在 HTML 中显示费率时,我会得到很好的输出,如 TAX: 23.0%。

但是,当用户从

我应该重写什么来支持此自定义映射?尝试覆盖 valueOf(String) 以错误结束。

I have a custom toString method in my enum:

enum TaxRate implements Serializable {
    RATE23(23.0),
    ...

    private String s
    private BigDecimal rate

    private TaxRate(BigDecimal s) {
        this.s = s + "%"
        this.rate = s * 0.01
    }

    public String toString() {
        return s
    }

Now when I display the rates in HTML I get nice output like TAX: 23.0%.

But what happens when a user selects the tax from a <select> and the sent value is i.e. 23.0% is that Grails can't create/get the TaxRate instance...

What should I override to support this custom mapping? Trying to override valueOf(String) ended with a error..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里°也失望 2025-01-15 08:39:19

您是否看过本页底部的条目?

如果您想在元素中使用带有“value”字符串属性(非常常见的习惯用法)的枚举,请尝试以下操作:

enum Rating {
    G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated")

    final String value

    Rating(String value) { this.value = value }

    String toString() { value }
    String getKey() { name() }
}

然后将 optionKey="key" 添加到您的代码中。

Have you seen the entry at the bottom of this page?

If you want to use a Enum with a "value" String attribute (a pretty common idiom) in a element, try this:

enum Rating {
    G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated")

    final String value

    Rating(String value) { this.value = value }

    String toString() { value }
    String getKey() { name() }
}

Then add optionKey="key" to your tag.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文