Java Code Examples for org.springframework.util.ReflectionUtils#setField()

The following examples show how to use org.springframework.util.ReflectionUtils#setField() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-content   File:    License: Apache License 2.0 6 votes vote down vote up
 * Sets object's field annotated with annotationClass to value only if the condition
 * matches.
 * @param domainObj the object containing the field
 * @param annotationClass the annotation to look for
 * @param value the value to set
 * @param condition the condition that must be satisfied to allow the match
public static void setFieldWithAnnotationConditionally(Object domainObj,
		Class<? extends Annotation> annotationClass, Object value,
		Condition condition) {

	Field field = findFieldWithAnnotation(domainObj, annotationClass);
	if (field != null && field.getAnnotation(annotationClass) != null
			&& condition.matches(field)) {
		try {
			PropertyDescriptor descriptor = org.springframework.beans.BeanUtils
					.getPropertyDescriptor(domainObj.getClass(), field.getName());
			if (descriptor != null) {
				BeanWrapper wrapper = new BeanWrapperImpl(domainObj);
				wrapper.setPropertyValue(field.getName(), value);
			else {
				ReflectionUtils.setField(field, domainObj, value);
		catch (IllegalArgumentException iae) {
Example 2
Source Project: DotCi   File:    License: MIT License 6 votes vote down vote up
public void onLoad(final ItemGroup<? extends Item> parent, final String name) throws IOException {
    try {
        final Field parentField = AbstractItem.class.getDeclaredField("parent");
        ReflectionUtils.setField(parentField, this, parent);
    } catch (final Exception e) {
        throw new RuntimeException(e);

    if (this.transientActions == null) {
        this.transientActions = new Vector<>();

Example 3
public void before() {

    Field instanceHandlerField = ReflectionUtils.findField(AssetCatalogRelationshipRESTService.class, "instanceHandler");
    ReflectionUtils.setField(instanceHandlerField, assetCatalogRelationshipService, instanceHandler);

    Field restExceptionHandlerField = ReflectionUtils.findField(AssetCatalogRelationshipRESTService.class, "restExceptionHandler");
    ReflectionUtils.setField(restExceptionHandlerField, assetCatalogRelationshipService, restExceptionHandler);

    response = mockRelationshipResponse();
Example 4
Source Project: bdf3   File:    License: Apache License 2.0 5 votes vote down vote up
public void apply(Object entity, Field field) {
	if (EntityUtils.isEntity(entity)) {
		EntityState state = EntityUtils.getState(entity);
		if (EntityState.NEW.equals(state)) {
			EntityUtils.setValue(entity, field.getName(), getValue(entity, field));	
	} else {
		ReflectionUtils.setField(field, entity, getValue(entity, field));
Example 5
public T get(ID id, Object... uriVariables) throws FirebaseRepositoryException {

    HttpEntity httpEntity = HttpEntityBuilder.create(firebaseObjectMapper, firebaseApplicationService).build();
    T response =, HttpMethod.GET, httpEntity, documentClass, uriVariables).getBody();
    if (response == null) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    } else {
        ReflectionUtils.setField(documentId, response, id);
        return response;
Example 6
 * Set the {@linkplain Field field} with the given {@code name}/{@code type}
 * on the provided {@code targetObject}/{@code targetClass} to the supplied
 * {@code value}.
 * <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()) {
				"Setting field '%s' of type [%s] on %s or target class [%s] to value [%s]", name, type,
				safeToString(targetObject), targetClass, value));
	ReflectionUtils.setField(field, targetObject, value);
Example 7
Source Project: JetfireCloud   File:    License: Apache License 2.0 5 votes vote down vote up
 * @param instance  实例对象
 * @param fieldName 成员变量名
 * @param value     值
public void setPrivateField(Object instance, String fieldName, Object value) {
    Field signingKeyField = ReflectionUtils.findField(instance.getClass(), fieldName);
    ReflectionUtils.setField(signingKeyField, instance, value);

Example 8
Source Project: Milkomeda   File:    License: MIT License 5 votes vote down vote up
 * 设置属性路径值
 * @param target    目标对象
 * @param fieldPath 属性路径
 * @param value     值
 * @since 3.7.1
public static void setFieldPath(Object target, String fieldPath, Object value) {
    Pair<Field, Object> fieldBundle = getFieldBundlePath(target, fieldPath);
    if (fieldBundle == null) {
    ReflectionUtils.setField(fieldBundle.getKey(), fieldBundle.getValue(), value);
Example 9
Source Project: mojito   File:    License: Apache License 2.0 5 votes vote down vote up
public RawDocument(CharSequence inputCharSequence, LocaleId sourceLocale, LocaleId targetLocale) {
    super(inputCharSequence, sourceLocale, targetLocale);

    Field inputURIField = ReflectionUtils.findField(RawDocument.class, "inputURI");

    try {
        URI fakeUri = new URI("/some/file/path/to/be/read/from/db");
        ReflectionUtils.setField(inputURIField, this, fakeUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
Example 10
Source Project: cloudbreak   File:    License: Apache License 2.0 5 votes vote down vote up
public static ConsulClient createClient(String apiAddress, int apiPort, TlsConfiguration tlsConfiguration) throws Exception {
    HttpClient httpClient = createHttpClient(tlsConfiguration.getClientCert(), tlsConfiguration.getClientKey(), tlsConfiguration.getServerCert());
    ConsulRawClient rawClient = new ConsulRawClient("https://" + apiAddress + ':' + apiPort, httpClient);
    Field agentAddress = ReflectionUtils.findField(ConsulRawClient.class, "agentAddress");
    ReflectionUtils.setField(agentAddress, rawClient, "https://" + apiAddress + ':' + apiPort + "/consul");
    return new ConsulClient(rawClient);
Example 11
private static void setId(Class<?> clazz, Object instance, String fieldName, Object value) {
	try {
		Field field = ReflectionUtils.findField(clazz, fieldName);
		int modifiers = field.getModifiers();
		Field modifierField = field.getClass().getDeclaredField("modifiers");
		modifiers = modifiers & ~Modifier.FINAL;
		modifierField.setInt(field, modifiers);
		ReflectionUtils.setField(field, instance, value);
	catch (ReflectiveOperationException e) {
		throw new IllegalArgumentException(e);
Example 12
public void setup() throws IllegalArgumentException, IllegalAccessException {
	cfCertTruster = new CloudFoundryCertificateTruster();
	Field envField = ReflectionUtils.findField(CloudFoundryCertificateTruster.class, "env");
	ReflectionUtils.setField(envField, cfCertTruster, env);
	Field sslCertTrusterField = ReflectionUtils.findField(CloudFoundryCertificateTruster.class,
	ReflectionUtils.setField(sslCertTrusterField, cfCertTruster, sslCertTruster);
Example 13
public void before() throws InvalidParameterException {

    governanceEngine = new GovernanceEngine(SERVER_NAME, SERVER_URL);
    Field connectorField = ReflectionUtils.findField(GovernanceEngine.class, "clientConnector");
    if (connectorField != null) {
        ReflectionUtils.setField(connectorField, governanceEngine, connector);
Example 14
public ClientHttpResponse execute() throws IOException {
    ClientHttpResponse response = delegate.execute();
    if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {"Token is invalid (got 401 response). Trying get a new token using the refresh token");

        String newToken = callback.refreshToken();
        if (newToken == null) {
            return response;
        } else {
  "New token obtained, retrying the request with it");
            // reflectively set the new token at the oauth2 interceptor (no nicer way, alas)
            for (ClientHttpRequestInterceptor interceptor: requestInterceptors) {
                if (interceptor.getClass().getName().equals("")) {
                    Field field = ReflectionUtils.findField(interceptor.getClass(), "accessToken");
                    ReflectionUtils.setField(field, interceptor, newToken);

            // create a new request, using the new token, but don't go through the refreshing factory again
            // because it may cause an endless loop if all tokens are invalid
            ClientHttpRequest newRequest = TokenRefreshingClientHttpRequestFactory.this.delegate.createRequest(delegate.getURI(), delegate.getMethod());
            return newRequest.execute();
    return response;
Example 15
public void setUp() {
	beanFactory = mock(DefaultListableBeanFactory.class);
	sentinelProperties = mock(SentinelProperties.class);
	sentinelHealthIndicator = new SentinelHealthIndicator(beanFactory,

	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "");

	heartbeatSender = mock(HeartbeatSender.class);
	Field heartbeatSenderField = ReflectionUtils
			.findField(HeartbeatSenderProvider.class, "heartbeatSender");
	ReflectionUtils.setField(heartbeatSenderField, null, heartbeatSender);
Example 16
Source Project: egeria   File:    License: Apache License 2.0 5 votes vote down vote up
public void before() throws Exception{


    Field connectorField = ReflectionUtils.findField(GlossaryViewClient.class, "clientConnector");
    ReflectionUtils.setField(connectorField, underTest, connector);

    response = new GlossaryViewEntityDetailResponse();

    glossaries.add(createGlossaryViewEntityDetail(GLOSSARY, "glossary-01"));
    glossaries.add(createGlossaryViewEntityDetail(GLOSSARY, "glossary-02"));
    glossaries.add(createGlossaryViewEntityDetail(GLOSSARY, "glossary-03"));

    categories.add(createGlossaryViewEntityDetail(CATEGORY, "category-01"));
    categories.add(createGlossaryViewEntityDetail(CATEGORY, "category-02"));
    categories.add(createGlossaryViewEntityDetail(CATEGORY, "category-03"));
    categories.add(createGlossaryViewEntityDetail(CATEGORY, "category-04"));
    categories.add(createGlossaryViewEntityDetail(CATEGORY, "category-05"));

    terms.add(createGlossaryViewEntityDetail(TERM, "term-01"));
    terms.add(createGlossaryViewEntityDetail(TERM, "term-02"));
    terms.add(createGlossaryViewEntityDetail(TERM, "term-03"));
    terms.add(createGlossaryViewEntityDetail(TERM, "term-04"));
    terms.add(createGlossaryViewEntityDetail(TERM, "term-05"));
    terms.add(createGlossaryViewEntityDetail(TERM, "term-06"));
    terms.add(createGlossaryViewEntityDetail(TERM, "term-07"));

    externalGlossaryLink = createGlossaryViewEntityDetail(EXTERNAL_GLOSSARY_LINK, "external-glossary-link-01");
Example 17
private static void enhanceVertx(String name, Vertx vertx) {
  if (StringUtils.isEmpty(name)) {
  Field field = ReflectionUtils.findField(VertxImpl.class, "eventLoopThreadFactory");
  VertxThreadFactory eventLoopThreadFactory = (VertxThreadFactory) ReflectionUtils.getField(field, vertx);

  field = ReflectionUtils.findField(eventLoopThreadFactory.getClass(), "prefix");

  String prefix = (String) ReflectionUtils.getField(field, eventLoopThreadFactory);
  ReflectionUtils.setField(field, eventLoopThreadFactory, name + "-" + prefix);
Example 18
Source Project: didi-eureka-server   File:    License: MIT License 4 votes vote down vote up
void setField(String name, Object value) {
	Field field = ReflectionUtils.findField(EurekaJacksonCodec.class, name);
	ReflectionUtils.setField(field, this, value);
Example 19
Source Project: DesignPatterns   File:    License: Apache License 2.0 4 votes vote down vote up
public static void setNullIfInvalid(CustomerRequestDetail detail, String columnName) {
    Field dataField = ReflectionUtils.findField(CustomerRequestDetail.class,columnName);
Example 20
 * 重写 setField 的方法,用于处理 setAccessible 的问题
 * @param field  Field
 * @param target Object
 * @param value  value
public static void setField(Field field, @Nullable Object target, @Nullable Object value) {
	ReflectionUtils.setField(field, target, value);