如何将String转换为Enum,然后再转换为大写? [英] How to convert String to Enum, changing to capital before that?

查看:48
本文介绍了如何将String转换为Enum,然后再转换为大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举

public enum Regular {
    NONE,
    HOURLY,
    DAILY,
    WEEKLY;

    public String getName() {
        return this.name().toLowerCase();
    }
}

在哪里可以将其转换为小写字母.但是,如果我要从String转换为Enum,则必须明确记住要设置 toUpperCase()

Where we could convert it to Lower case when we get it. But if I were to convert from String to Enum, I have to explicitly remember to set toUpperCase()

Regular.valueOf(regular.toUpperCase());

在我的Enum类中是否可以定义此方法,它将自动将所有字符串转换为UpperCase以进行比较?

Is there a way to define this in my Enum class, where it will auto convert all string to UpperCase to compare it?

推荐答案

不,没有办法.

但是,一旦创建了另一个方法 String getName()来覆盖" name()的默认实现.我认为您必须对 Regular valueOf()做同样的事情,即创建另一个方法 Regular valueOfByName().

But, once you create another method String getName() to "override" the default implementation of name(). I thought that you have to do the same with Regular valueOf() ,i.e., create another method Regular valueOfByName().

public enum Regular {
    NONE,
    HOURLY,
    DAILY,
    WEEKLY;

    public String getName() {
        return this.name().toLowerCase();
    }

    public static Regular valueOfByName(String name){
        return valueOf(name.toUpperCase());
    }
}

这篇关于如何将String转换为Enum,然后再转换为大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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