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();
}
}