简体   繁体   English

在Java中,如何在枚举本身中获取枚举的值?

[英]In Java, how do I get the value of an enum inside the enum itself?

I want to override toString() for my enum, Color . 我想覆盖toString()为我的枚举, Color However, I can't figure out how to get the value of an instance of Color inside the Color enum. 但是,我无法弄清楚如何在Color枚举中获取Color实例的值。 Is there a way to do this in Java? 有没有办法在Java中这样做?

Example: 例:

public enum Color {
    RED,
    GREEN,
    BLUE,
    ...

    public String toString() {
        // return "R" for RED, "G", for GREEN, etc.
    }
}
public enum Color {
    RED("R"),
    GREEN("G"),
    BLUE("B");

    private final String str;
    private Color(String s){
        str = s;
    }
    @Override
    public String toString() {
        return str;
    }
}

You can use constructors for Enums. 您可以为Enums使用构造函数。 I haven't tested the syntax, but this is the idea. 我没有测试语法,但这是个主意。

You can also switch on the type of this , for example: 您也可以打开的类型this ,例如:

public enum Foo { 
  A, B, C, D 
  ; 
  @Override 
  public String toString() { 
    switch (this) { 
      case A: return "AYE"; 
      case B: return "BEE"; 
      case C: return "SEE"; 
      case D: return "DEE"; 
      default: throw new IllegalStateException(); 
    } 
  } 
} 

Enum.name() - who'd of thunk it? Enum.name() - 谁是thunk?

However, in most cases it makes more sense to keep any extra information in an instance variable that is set int the constructor. 但是,在大多数情况下,将任何额外信息保存在构造函数中设置的实例变量中更有意义。

Use super and String.substring() : 使用superString.substring()

public enum Color
{
    RED,
    GREEN,
    BLUE;

    public String toString()
    {
        return "The color is " + super.toString().substring(0, 1);
    }
}

Java does this for you by default, it returns the .name() in .toString(), you only need to override toString() if you want something DIFFERENT from the name. Java默认为您执行此操作,它返回.toString()中的.name(),如果您想要名称中的DIFFERENT,则只需覆盖toString()。 The interesting methods are .name() and .ordinal() and .valueOf(). 有趣的方法是.name()和.ordinal()和.valueOf()。

To do what you want you would do 做你想做的事你会做

.toString(this.name().substring(1));

What you might want to do instead is add an attribute called abbreviation and add it to the constructor, add a getAbbreviation() and use that instead of .toString() 您可能想要做的是添加一个名为abbreviation的属性并将其添加到构造函数中,添加一个getAbbreviation()并使用它来代替.toString()

I've found something like this (not tested tho): 我发现了这样的东西(未经过测试):

public enum Color {
RED{
public String toString() {
    return "this is red";
}
},
GREEN{
public String toString() {
    return "this is green";
}
},
...   

} }

Hope it helps a bit ! 希望它有点帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM