使用枚举值作为字符串文字

问题:

使用存储在枚举中的值作为字符串的最佳方式是什么?
例如:

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

然后,我可以使用Mode.mode1将其字符串表示形式返回为mode1。无需继续调用Mode.model.toString()

回答:

你不行我想你在这里有四个选择。所有这四个都提供了一个解决方案,但是有一点不同
 选项一: use the built-in name() on an enum

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

 选项二: 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;
    }
}

 选项三: 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() { }
}

 选项四: 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";  
}

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Using Enum values as String literals

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

+ 28 = 33