[英]Java enums vs constants for Strings
I've switched from using constants for Strings to using enums. 我已经从使用常量字符串切换到使用枚举。 Many times I need the
String
representation of the enum (for logging, to pass to an API that requires a String
, etc). 很多时候我需要枚举的
String
表示形式(用于记录,传递给需要String
的API等)。
With String
constants, you can just pass the String value, but with enums you have to call toString()
. 使用
String
常量,您只需传递String值,但是使用枚举,您必须调用toString()
。 Is there a way you can "default" to the String value when supplying the enum variable? 有没有办法在提供枚举变量时“默认”为String值?
As many posters have commented, perhaps one shouldn't be using enums if you frequently need the String
representation. 正如许多海报所评论的那样,如果您经常需要
String
表示,也许不应该使用枚举。
You should fully adopt enum
and not use the String
representation in the first place. 您应该完全采用
enum
而不是首先使用String
表示。 Only use the toString()
to generate messages, logs, etc, but internally you'd want to work with enum
. 仅使用
toString()
生成消息,日志等,但在内部您需要使用enum
。 Any Map
, Set
, etc operations should be done on the enum
type, which guarantees proper serialization, singleton pattern, and everything else that enum
types are supposed to have. 任何
Map
, Set
等操作都应该在enum
类型上完成,这样可以保证正确的序列化,单例模式以及enum
类型应该具有的所有其他内容。
In your snippet: 在你的片段中:
Object o = map.get(Options.OPTION_1);
//This won't work as intended if the Map key is a String
Compile-time error aside, you should really question whether the map key should even be of type String
in the first place. 除了编译时错误之外,你应该首先询问地图键是否应该首先是
String
类型。 The way you're using it, it looks like it should be a Map<Options, Something>
. 你使用它的方式,它看起来应该是
Map<Options, Something>
。
There are a lot of good reasons to use Enum
in Java. 在Java中使用
Enum
有很多很好的理由。 But not if you only need a String
. 但是如果你只需要一个
String
不了。
For example, if you are representing a specific set of entities and don't want them to be type-equivalent with other kinds of things (like String
s), then an Enum
would be appropriate. 例如,如果您表示一组特定的实体,并且不希望它们与其他类型的事物(如
String
)等效,那么Enum
将是合适的。 Moreso if you are going to be calling functions that operate them and differentiate based on the particular instance. 此外,如果您要调用操作它们的函数并根据特定实例进行区分。
On the other hand, if you are only interested in the String
value of something, then there is nothing wrong with a String
constant. 另一方面,如果你只对某些东西的
String
值感兴趣,那么String
常量没有任何问题。
From what you've posted, I can't tell what the use case is. 根据您发布的内容,我无法确定用例是什么。 Is there some reason you need to use
Enum
here? 你有什么理由需要在这里使用
Enum
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.