我不喜欢有很多 if-else 的代码。所以,这是我对同样问题的解决方案。
枚举类型:
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;
}
}
}
ReflectionHelper 的方法:
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();
}
}