Update August 28, 2021
I have written a follow-up that improves on the following
solution using a type conversion operator overload.
When I started dabbling in C#, I wondered if it supports values in
enums. In Java, an enum instance can have properties (called fields in
Java lingo) associated with the enum’s literals. By taking advantage
of this feature, you can encode more information in an enum, like a
string, for example, or a constant number. You can even embed
instantiated class objects, maybe to associate an object factory with
a literal.
In my use case, I wanted to achieve a form of a key-value-pair
mapping. I require certain illegal characters in the NTFS file or
directory names to be replaced with a given code. I use HTML encoding
for my needs because I can simply look up the values online if I need
to.
Here is the Java reference example. First, let me start with the basic
enum definition (I use Lombok to auto-generate boilerplate code like
the constructor and accessors).
@Getter
@RequiredArgsConstructor
enum CharacterReplacementCode {
COLON(":", "&58;"),
POUND("#", "&35;"),
QUESTION_MARK("?", "&63;");
private final String character;
private final String replacement;
@Override
public String toString() {
return String.format("Character '%s' substituted by code '%s'", character, replacement);
}
}
Read More »