Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

java - How to access an unknown enum's "valueOf()" method

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

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

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...