简体   繁体   中英

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).

With String constants, you can just pass the String value, but with enums you have to call toString() . Is there a way you can "default" to the String value when supplying the enum variable?

As many posters have commented, perhaps one shouldn't be using enums if you frequently need the String representation.

You should fully adopt enum and not use the String representation in the first place. Only use the toString() to generate messages, logs, etc, but internally you'd want to work with 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.

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. The way you're using it, it looks like it should be a Map<Options, Something> .

There are a lot of good reasons to use Enum in Java. But not if you only need a 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. 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.

From what you've posted, I can't tell what the use case is. Is there some reason you need to use Enum here?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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