使用存储在枚举中的值作为字符串文字的最佳方法是什么?

public enum Modes {
    some-really-long-string,
    mode1,
    mode2,
    mode3
}

然后,我可以使用Mode.mode1将其字符串表示形式返回为mode1.不用一直打Mode.mode1.toString().

推荐答案

你不能.我想你有四个 Select .这四个人都提供了解决方案,但方法略有不同.

Option One: use the built-in 100 on an enum. This is perfectly fine if you don't need any special naming format.

    String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.

Option Two: add overriding properties to your enums if you want more control

public enum Modes {
    mode1 ("Fancy Mode 1"),
    mode2 ("Fancy Mode 2"),
    mode3 ("Fancy Mode 3");

    private final String name;       

    private Modes(String s) {
        name = s;
    }

    public boolean equalsName(String otherName) {
        // (otherName == null) check is not needed because name.equals(null) returns false 
        return name.equals(otherName);
    }

    public String toString() {
       return this.name;
    }
}

Option Three: use static finals instead of enums:

public final class Modes {

    public static final String MODE_1 = "Fancy Mode 1";
    public static final String MODE_2 = "Fancy Mode 2";
    public static final String MODE_3 = "Fancy Mode 3";

    private Modes() { }
}

Option Four: interfaces have every field public, static and final:

public interface Modes {

    String MODE_1 = "Fancy Mode 1";
    String MODE_2 = "Fancy Mode 2";
    String MODE_3 = "Fancy Mode 3";  
}

Java相关问答推荐

android Document File. isDirector()返回意外结果

将偶数元素移动到数组的前面,同时保持相对顺序

我应该避免在Android中创建类并在运行时编译它们吗?

嵌入式ActiveMQ Artemis Web控制台加载错误

当涉及到泛型时,类型推理在Java中是如何工作的?

在Java中如何从Executors.newFixedThreadPool(MAX_THREAD_COUNT())迁移到虚拟线程

JOOQ中的子查询使用的是默认方言,而不是配置的方言

如何在Microronaut中将 map 读取为 map

未找到适用于响应类型[类java.io.InputStream]和内容类型[Text/CSV]的HttpMessageConverter

声明MessageChannel Bean的首选方式

虚拟线程应该很快消亡吗?

使用Class.this.field=Value初始化构造函数中的最后一个字段会产生错误,而使用this.field=Value则不会

如何处理两个几乎相同的XSD文件?

从12小时开始的日期模式

嘲笑黄瓜中的对象

如何在Java中使用正则表达式拆分字符串

未调用OnBackPressedCallback-Activitiy立即终止

Android无法在Java代码中调用Kotlin代码,原因是在Companion中使用Kotlin枚举时

TinyDB问题,无法解析符号';上下文&

如何使用带有可选参数的类生成器?