Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have configuration files which can be populated with enums and their respective values and will then be read by my program.

For example, a configuration file (yaml format) may look like this:

SomeEnumClass:
- VALUE_A_OF_SOME_ENUM
- VALUE_B_OF_SOME_ENUM
- ANOTHER_VALUE

AnotherEnumClass:
- VALUE_1
- VALUE_3
- VALUE_3
- VALUE_7
[etc...]

Unfortunately this leads to duplication in my code (java) like this:

if (enumNameString.equals("SomeEnumClass")) {
    Collection<SomeEnumClass> values = new ArrayList<>;
    for (String listEntry : yamlConfig.getStringList(enumNameString)) {
        values.add(SomeEnumClass.valueOf(listEntry));
    }
    return values;

} else if (enumNameString.equals("AnotherEnumClass")) {
    Collection<AnotherEnumClass> values = new ArrayList<>;
    for (String listEntry : yamlConfig.getStringList(enumNameString)) {
        values.add(AnotherEnumClass.valueOf(listEntry));
    }
    return values;

} else if ...
} else if ...
} else if ...

(please keep in mind that this example is pseudo code)

So of course i'm trying to get rid of the duplicate code. But how? Is it possible to:

  1. Get a class from a string? ("SomeEnumClass" -> SomeEnumClass.class)
  2. Then check if that class is castable to Enum or something?
  3. Access the enum's valueOf() method from that cast?
question from:https://stackoverflow.com/questions/65952514/how-to-access-an-unknown-enums-valueof-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can create a Map<String, Class<?>> which contains the mapping like this:

private static final Map<String, Class<Enum<?>>> MAP;
static {
    Map<String, Class<Enum<?>>> map = new HashMap<>();
    map.put(SomeEnumClass.class.getSimpleName(), SomeEnumClass.class);
    // your other enum classes

    MAP = Collections.unmodifiableMap(map);
}

And then you can make use of Enum.valueOf(Class<Enum>, String):

Class<Enum<?>> enumClass = MAP.get(enumNameString);
if (enumClass != null) {
    Collection<Enum<?>> values = new ArrayList<>;
    for (String listEntry : yamlConfig.getStringList(enumNameString)) {
        values.add(Enum.valueOf(enumClass, listEntry));
    }
    return values;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...