2014-09-19 452 views
1

我已经看到许多StackOverflow帖子关于如何动态获取枚举的值,因为你知道编译时Enum类,但我试图动态加载枚举类和枚举值,我没有看到如何做到这一点。动态加载Java枚举类和枚举常量

我试图做这样的事情:

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

所以你想使用反射? – msrd0 2014-09-19 16:48:34

回答

4

如果你知道(或可以找出)你想从装载值枚举的完全合格的类名,你可以做这个:

String enumClassName = "com.mycompany.MyEnum"; 
String enumConstant = "MyValue"; 

Class enumClass = Class.forName(enumClassName); 
Object enumValue = Enum.valueOf(enumClass, enumConstant); 

assert enumValue == MyEnum.MyValue; // passes 
+0

谢谢,@Dan Vinton! 'Class.forName'是我所需要的。出于某种原因,我有一个心理障碍,我不能用普通的旧反射来枚举Enum,所以这解决了我的问题。 – 2014-09-19 18:11:08

-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); 
    } 
} 
+0

建议编辑:'抛出ClassNotFoundException,NoSuchMethodException,...'抛出ReflectiveOperationException' – msrd0 2014-09-19 17:09:10

+0

感谢您的回答。尽管这个答案包含了我需要的行和概念('class.forName()'),我接受了上面的答案,因为它更简洁地解决了我的问题。 – 2014-09-19 18:12:37

+0

为什么在类Enum中有一个方法可以完全按照你想要的方法来进行反射呢? 'public static > T valueOf(Class enumType,String name)' – 2014-09-20 00:22:11