我有一个反射实用程序。此类的目的是强制转换通过反射获得的某些字段的值。
我提供了代码:
/**
* Get the field values with the types already listed according to the field type
*
* @param clazz clazz
* @param fieldName fieldName
* @param fieldValue fieldValue
* @return value cast to specific field type
*/
public static Object castFieldValue(Class<?> clazz, String fieldName, Object fieldValue) {
Field field = getField(clazz, fieldName)
.orElseThrow(() -> new IllegalArgumentException("Cannot find field name:" + fieldName));
Class<?> fieldType = field.getType();
if (fieldType.isAssignableFrom(Double.class)) {
if (fieldValue instanceof String) {
return Double.valueOf((String)fieldValue);
}
return ((Number) fieldValue).doubleValue();
}
if (fieldType.isAssignableFrom(Long.class)) {
if (fieldValue instanceof String) {
return Long.valueOf((String)fieldValue);
}
return ((Number) fieldValue).longValue();
}
if (fieldType.isAssignableFrom(Float.class)) {
if (fieldValue instanceof String) {
return Float.valueOf((String)fieldValue);
}
return ((Number) fieldValue).floatValue();
}
if (fieldType.isAssignableFrom(Integer.class)) {
if (fieldValue instanceof String) {
return Integer.valueOf((String)fieldValue);
}
return ((Number) fieldValue).intValue();
}
if (fieldType.isAssignableFrom(Short.class)) {
if (fieldValue instanceof String) {
return Short.valueOf((String)fieldValue);
}
return ((Number) fieldValue).shortValue();
}
return fieldValue;
}
public static Optional<Field> getField(Class<?> clazz, String fieldName) {
Field[] fields = getAllFields(clazz);
return Stream.of(fields)
.filter(x -> x.getName().equals(fieldName))
.findFirst();
}
public static Field[] getAllFields(Class<?> clazz) {
if (clazz == null) return null;
List<Field> fields = new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()));
if (clazz.getSuperclass() != null) {
// danger! Recursion
fields.addAll(Arrays.asList(getAllFields(clazz.getSuperclass())));
}
return fields.toArray(new Field[] {});
}
此代码非常冗长。有可能以某种方式简化它吗?
这是一段重复很小的更改重复的代码:
if (fieldType.isAssignableFrom(Short.class)) {
if (fieldValue instanceof String) {
return Short.valueOf((String)fieldValue);
}
return ((Number) fieldValue).shortValue();
}
如果我再次澄清方法的用途,它会根据类字段的类型得出正确的值类型。