我想設定一些枚舉的默認值,我使用下面的方法設置的枚舉值:提取,並通過反射
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());
}
}
的問題實際上是設置枚舉。我已經提取了枚舉類型,但是然後調用MethodInvoker。傳入Enum對象證明是一個問題。所有枚舉都具有以下內容作爲枚舉數組的最後一個元素。
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]);
是不是我的設置枚舉
:EnumName.UNKNOWN
然而,這不被通過,它看起來像invoke方法設置
你看到一個異常? 'invoke'中'newValue'的值是'null',還是你的枚舉之一? –
你的代碼有點複雜。你的'invoke'方法沒有一個可以設置枚舉的對象實例。你只是傳遞一個方法名和一個枚舉值...你真的沒有機會在構造函數中做這件事嗎? – Kai