gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:29 24 4
gpt4 key购买 nike

我想为我的枚举 Color 覆盖 toString()。但是,我无法弄清楚如何在 Color 枚举中获取 Color 实例的值。有没有办法在 Java 中执行此操作?

例子:

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

public String toString() {
// return "R" for RED, "G", for GREEN, etc.
}
}

最佳答案

也可以开启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();
}
}
}

关于java - 在 Java 中,如何在枚举本身中获取枚举的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2321754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com