我有使用其setter方法設置對象的值的代碼。其中一個設置器將Enum類型作爲方法參數。該代碼看起來是這樣的:如何將字符串轉換爲枚舉值枚舉類型引用是一個類<?>?
String value = "EnumValue1";
Method setter = getBeanWriteMethod("setMyEnumValue");
Class<?> type = setter.getParameterTypes()[0];
Object convertedValue = null;
if (type.isEnum()) {
convertedValue = convertToEnum(value, type);
} else {
convertedValue = ClassUtils.convertType(value, type);
}
return convertedValue;
的問題是要放什麼東西在convertToEnum
方法。我知道我可以通過遍歷type
對象的枚舉常量(或字段)來匹配值來「蠻力」。我是否忽略了使用反射來做到這一點的更簡單的方法? (我看了幾個例子,但沒有找到任何地方的枚舉只知道通過類)。
謝謝,當我第一次嘗試時,我一定得到了錯誤。這是正確的解決方案。不幸的是,在嘗試這些之後,我發現我需要做一個不區分大小寫的匹配,而Enum.valueOf()不會這樣做。所以回到蠻力的方法... –
這種情況是可怕的。 'type'不是'Enum.class'。無論如何,'asSubclass'比黑客演員要好。 –
@ TomHawtin-tackline:使用asSubclass給我編譯警告。 '類<?擴展枚舉> enumClass = type.asSubclass(Enum.class); Enum > convertedValue = Enum.valueOf(enumClass,「Value1」);'對於Raw Type和Unvhecked Invocation。所以我不確定我看到那樣更好。 –