List of usage examples for org.springframework.util ReflectionUtils setField
public static void setField(Field field, @Nullable Object target, @Nullable Object value)
From source file:org.springframework.test.util.ReflectionTestUtils.java
/** * Set the {@linkplain Field field} with the given {@code name}/{@code type} * on the provided {@code targetObject}/{@code targetClass} to the supplied * {@code value}./*from ww w . j av a 2s .c om*/ * <p>If the supplied {@code targetObject} is a <em>proxy</em>, it will * be {@linkplain AopTestUtils#getUltimateTargetObject unwrapped} allowing * the field to be set on the ultimate target of the proxy. * <p>This method traverses the class hierarchy in search of the desired * field. In addition, an attempt will be made to make non-{@code public} * fields <em>accessible</em>, thus allowing one to set {@code protected}, * {@code private}, and <em>package-private</em> fields. * @param targetObject the target object on which to set the field; may be * {@code null} if the field is static * @param targetClass the target class on which to set the field; may * be {@code null} if the field is an instance field * @param name the name of the field to set; may be {@code null} if * {@code type} is specified * @param value the value to set * @param type the type of the field to set; may be {@code null} if * {@code name} is specified * @since 4.2 * @see ReflectionUtils#findField(Class, String, Class) * @see ReflectionUtils#makeAccessible(Field) * @see ReflectionUtils#setField(Field, Object, Object) * @see AopTestUtils#getUltimateTargetObject(Object) */ public static void setField(@Nullable Object targetObject, @Nullable Class<?> targetClass, @Nullable String name, @Nullable Object value, @Nullable Class<?> type) { Assert.isTrue(targetObject != null || targetClass != null, "Either targetObject or targetClass for the field must be specified"); if (targetObject != null && springAopPresent) { targetObject = AopTestUtils.getUltimateTargetObject(targetObject); } if (targetClass == null) { targetClass = targetObject.getClass(); } Field field = ReflectionUtils.findField(targetClass, name, type); if (field == null) { throw new IllegalArgumentException( String.format("Could not find field '%s' of type [%s] on %s or target class [%s]", name, type, safeToString(targetObject), targetClass)); } if (logger.isDebugEnabled()) { logger.debug(String.format("Setting field '%s' of type [%s] on %s or target class [%s] to value [%s]", name, type, safeToString(targetObject), targetClass, value)); } ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, targetObject, value); }