Java - 枚举 valueOf“覆盖”命名约定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19153569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - enum valueOf "override" naming convention
提问by Alin Stoian
Say you have the following enum:
假设您有以下枚举:
public enum Color {
RED("R"), GREEN("G"), BLUE("B");
private String shortName;
private Color(String shortName) {
this.shortName = shortName;
}
public static Color getColorByName(String shortName) {
for (Color color : Color.values()) {
if (color.shortName.equals(shortName)) {
return color;
}
}
throw new IllegalArgumentException("Illegal color name: " + shortName);
}
}
Since enum is a special case, when you cannot just override the valueOf function, what is the naming convention for circumventing this and implementing valueOf(String name)?
由于 enum 是一种特殊情况,当您不能只覆盖 valueOf 函数时,绕过这个并实现 valueOf(String name) 的命名约定是什么?
getColorByName(String name)
getValueOf(String name)
permissiveValueOf(String name)
customValueOf(String name)
forName(String name)
getEnum(String name)
getColor(String name)
Later Edit: I see that Bloch in Effective Java 2nd ed. proposes something in the lines of getInstance() (Chapter 1, Item 1). Just to add another option.
稍后编辑:我在 Effective Java 2nd ed 中看到了 Bloch。在 getInstance()(第 1 章,第 1 项)的几行中提出了一些建议。只是为了添加另一个选项。
采纳答案by Guillaume Poussel
You are definitely right, you cannot override Enum#valueOf()
since it is a static method of Enum
class.
你绝对是对的,你不能重写,Enum#valueOf()
因为它是Enum
类的静态方法。
I don't think there is a naming convention. As you have already pointed out, there are few examples in Java:
我认为没有命名约定。正如您已经指出的那样,Java 中的示例很少:
I won't use getEnum
, since you are not getting the Enum
itself, but rather a value.
Using forName()
is not appropriate here, R
is not the nameof the red color.
我不会使用getEnum
,因为你得到的不是Enum
它本身,而是一个值。用forName()
在这里不合适,R
不是 红色的名字。
I would rather go with:
我宁愿去:
fromString()
since it is an opposite totoString()
;getColor()
for consistency with Java Standard Library.
fromString()
因为它与toString()
;getColor()
为了与 Java 标准库保持一致。
回答by alterfox
I would use the pair:
我会使用这对:
Color fromValue(String value)
String toValue()
This is something that I've found most suitable in my enums.
这是我在枚举中发现的最合适的东西。
回答by Ravindra HV
Do consider the following as well!
也请考虑以下事项!
Color fromName(String name);
Color fromShortName(String shortName);
Color fromCode(String code);