我已经看过很多关于如何在编译时知道Enum类动态获取枚举值的StackOverflow帖子,但我试图动态加载枚举类和枚举值,我不是看看如何做到这一点。
我正在尝试做这样的事情:
public interface Config {
public ConfigValue getConfigValue();
}
public enum AwsConfig implements Config {
ACCESS_KEY_ID( new ConfigValue(...) ),
API_URL( new ConfigValue(...) )
...
public static String getName() { return "AwsConfig"; }
...
}
public enum PaginatorConfig implements Config {
DEFAULT_PAGE_SIZE( new ConfigValue(...) ),
...
public static String getName() { return "PaginatorConfig"; }
...
}
public void myMethod( ConfigValue configValue ) {
String enumClassName = configValue.getName();
String enumConstantKeyName = configValue.getKey();
// I now have the enum's class name as enumClassName
// I now have the enum constant's name as enumConstantKeyName
// How can I dynamically get the enum constant's configValue based on the enumClassName and enumConstantKeyName?
// I know I can get the value dynamically if I know the Enum constant...
ConfigValue configValue = AwsConfig.valueOf("API_URL")
// But I wish I could do something like this...
ConfigValue configValue = Enum.valueOf( "AwsConfig", "API_URL" );
}
答案 0 :(得分:5)
如果您知道(或可以弄清楚)要从中加载值的枚举的完全限定类名,则可以执行以下操作:
String enumClassName = "com.mycompany.MyEnum";
String enumConstant = "MyValue";
Class enumClass = Class.forName(enumClassName);
Object enumValue = Enum.valueOf(enumClass, enumConstant);
assert enumValue == MyEnum.MyValue; // passes
答案 1 :(得分:-1)
您可以使用反射。这是一个简短的例子:
public class Test {
public enum TestEnum {
MyEnumValue1,
MyEnumValue2;
}
public static void main(String[] args) {
try {
Object enumValue = getEnumValue("test.Test$TestEnum", "MyEnumValue2");
System.out.println(enumValue.getClass().getName() + " = "
+ enumValue);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static Object getEnumValue(String enumClassName, String enumValueName)
throws ClassNotFoundException, NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Class<?> enumClass = Class.forName(enumClassName);
Method valueOfMethod = enumClass.getDeclaredMethod("valueOf",
String.class);
return valueOfMethod.invoke(null, enumValueName);
}
}