通过反射提取和设置枚举值

时间:2011-09-01 09:36:00

标签: java reflection enums

我正在尝试将多个枚举设置为默认值我使用以下方法:

private void checkEnum(Field field, String setMethod) {
    // TODO Auto-generated method stub
    try {
        String className = Character.toUpperCase(field.getName().charAt(0)) +
        field.getName().substring(1);
        Class<?> cls = Class.forName("com.citigroup.get.zcc.intf." + className);
        Object[] enumArray = cls.getEnumConstants();

        //set to the last Enum which is unknown
        invoke(setMethod, enumArray[enumArray.length - 1] );
    } catch(Exception e) {
        System.out.println(e.toString());
    }
}    

问题实际上是设置Enum。我已经提取了枚举类型,但后来调用了MethodInvoker。传入Enum对象证明是一个问题。所有枚举都具有以下作为枚举数组的最后一个元素。

EnumName.UNKNOWN

但是,这不是通过调用方法设置的,如下所示:

private Object invoke(String methodName, Object newValue) {
    Object value = null;
    try {
        methodInvoker.setTargetMethod(methodName);

        if (newValue != null) {
            methodInvoker.setArguments(new Object[]{newValue});
        } else {
            methodInvoker.setArguments(new Object[]{});             
            }
        methodInvoker.prepare();
        value = methodInvoker.invoke();
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
    } catch (java.lang.reflect.InvocationTargetException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
    }

    return value;
}

所以我迷失了为什么

invoke(setMethod, enumArray[enumArray.length -1] );

没有设置我的枚举

1 个答案:

答案 0 :(得分:3)

我试图让你的代码运行。 methodInvoker.prepare()调用抛出: java.lang.IllegalArgumentException:需要'targetClass'或'targetObject'

所以我在类中添加了缺少参数并且代码可以工作,如果我理解你的用例。 您似乎正在设置一个静态字段,其名称必须是com.citigroup.get.zcc.intf下Enum类的名称,并且字段名称中的第一个字符为downcased。

这是我修改后的代码:

    public void checkEnum(Field field, String setMethod, Class clazz) {
      try {
        String className = Character.toUpperCase(field.getName().charAt(0)) +
            field.getName().substring(1);
        Class<?> cls = Class.forName("com.citigroup.get.zcc.intf." + className);
        Object[] enumArray = cls.getEnumConstants();

        //set to the last Enum which is unknown
        invoke(setMethod, enumArray[enumArray.length - 1], clazz);
      } catch (Exception e) {
        System.out.println(e.toString());
      }
    }
    private Object invoke(String methodName, Object newValue, Class clazz) {
      Object value = null;
      try {
        MethodInvoker methodInvoker = new MethodInvoker(); // this was missing
        methodInvoker.setTargetMethod(methodName);
        methodInvoker.setTargetClass(clazz);  // This was missing

        if (newValue != null) {
          methodInvoker.setArguments(new Object[]{newValue});
        } else {
          methodInvoker.setArguments(new Object[]{});
        }
        methodInvoker.prepare();
        value = methodInvoker.invoke();
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
      } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
      } catch (java.lang.reflect.InvocationTargetException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
      } catch (IllegalAccessException e) {
        throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
      }

      return value;
    }
  }

我的测试代码类似于(Show是我的枚举类,MethodNameHelper之前已发布到StackExchange):

public class StackExchangeTestCase {
  protected static final Logger log = Logger.getLogger(StackExchangeTestCase.class);
  public static Show show;
  public static void setShow(Show newShow) {
    show = newShow;
  }

  @Test
  public void testJunk() throws Exception {

    Method me = (new Util.MethodNameHelper(){}).getMethod();
    Class<?> aClass = me.getDeclaringClass();
    Field att1 = aClass.getField("show");
    show = null;

    methodNameHelper.checkEnum(att1, "setShow", aClass);

    System.out.println(show); // worked
  }
}