Add setField(target:Object, fieldName:String, value:Object) method to ReflectionUtils to set fields of an Object.

This commit is contained in:
John Blum
2019-10-29 15:04:53 -07:00
parent 368caf601a
commit 90fc5209f7

View File

@@ -21,6 +21,7 @@ import java.lang.reflect.Method;
import java.util.Optional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* Utility {@link Class} for performing reflective and introspective Java {@link Object} operations.
@@ -67,4 +68,30 @@ public abstract class ReflectionUtils extends org.springframework.util.Reflectio
makeAccessible(method);
return method;
}
public static <T> Object setField(T target, String fieldName, Object value) throws NoSuchFieldException {
Assert.notNull(target, "Target object must not be null");
Assert.hasText(fieldName, String.format("Field name [%s] must be specified", fieldName));
Field field = findField(target.getClass(), fieldName);
if (field != null) {
Class<?> fieldType = field.getType();
Assert.isTrue(value == null || fieldType.isInstance(value),
String.format("The value type [%1$s] is not assignment compatible with the field type [%2$s]",
ObjectUtils.nullSafeClassName(value), fieldType.getName()));
makeAccessibleReturnField(field);
setField(field, target, value);
return target;
}
else {
throw new NoSuchFieldException(String.format("Field [%s] was not found on Object of type [%s]",
fieldName, target.getClass().getName()));
}
}
}