我不喜歡有許多如 - 代碼其他。所以,這裏是我同一個問題的解決方案。
枚舉爲類型:ReflectionHelper的
public enum Types {
BYTE,
BOOLEAN,
SHORT,
CHAR,
INT,
FLOAT,
LONG,
DOUBLE,
OBJECT;
private static final String ALL_TYPES_STRING = Arrays.toString(Types.values());
public static Types getType(Class<?> clazz) {
String className = clazz.getSimpleName().toUpperCase();
if (ALL_TYPES_STRING.contains(className)) {
return Types.valueOf(className);
} else {
return Types.OBJECT;
}
}
}
方法:
public static void setFieldValue(Object object,
String fieldName,
String value) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Types types = Types.getType(field.getType());
switch (types) {
case BYTE:
field.set(object, Byte.valueOf(value));
break;
case BOOLEAN:
field.set(object, Boolean.valueOf(value));
break;
case SHORT:
field.set(object, Short.valueOf(value));
break;
case CHAR:
field.set(object, value.charAt(0));
break;
case INT:
field.set(object, Integer.decode(value));
break;
case FLOAT:
field.set(object, Float.valueOf(value));
break;
case LONG:
field.set(object, Long.valueOf(value));
break;
case DOUBLE:
field.set(object, Double.valueOf(value));
break;
case OBJECT:
default:
field.set(object, value);
}
field.setAccessible(false);
} catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
'decimal'和'java.math.BigDecimal'不是原始類型。 – 2013-02-17 09:51:18