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

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

本文介绍了使用枚举值作为字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案

你不行我想你有四个选择。所有四个都提供了一个解决方案,但是有一个稍微不同的方法...



选项一: 使用内置的 name()在枚举上

  String name = Modes.mode1 。名称(); //返回此枚举常量的名称,与其枚举声明中声明的完全相同。 

选项二: 添加覆盖属性到你的枚举,如果你想要更多的控制

  public enum模式{
mode1(花式模式1),
mode2(花式模式2),
mode3(花式模式3);

private final String name;

私人模式(String s){
name = s;
}

public boolean equalsName(String otherName){
//(otherName == null)不需要检查,因为name.equals(null)返回false
return name.equals(otherName);
}

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

选项三: em>使用静态决赛而不是枚举:

  public final class模式{

public static final String MODE_1 =花式模式1;
public static final String MODE_2 =花式模式2;
public static final String MODE_3 =Fancy Mode 3;

私人模式(){}
}

选项四:界面有每个字段都是public,static和final:

  public界面模式{

String MODE_1 =花式模式1;
字符串MODE_2 =花式模式2;
字符串MODE_3 =花式模式3;
}


What is the best way to use the values stored in an Enum as String literals?For example:

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

Then later I could use Mode.mode1 to return its string representation as mode1. Without having to keep calling Mode.model.toString().

解决方案

You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...

Option One: 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.

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";
}

这篇关于使用枚举值作为字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:24