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

The following examples show how to use org.springframework.util.ReflectionUtils#setField() . These examples are extracted from open source projects. 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: BeanUtils.java    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);
				return;
			}
			else {
				ReflectionUtils.setField(field, domainObj, value);
			}
			return;
		}
		catch (IllegalArgumentException iae) {
		}
	}
}
 
Example 2
Source Project: DotCi   File: DynamicSubProject.java    License: MIT License 6 votes vote down vote up
@Override
public void onLoad(final ItemGroup<? extends Item> parent, final String name) throws IOException {
    try {
        final Field parentField = AbstractItem.class.getDeclaredField("parent");
        parentField.setAccessible(true);
        ReflectionUtils.setField(parentField, this, parent);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    doSetName(name);
    if (this.transientActions == null) {
        this.transientActions = new Vector<>();
    }
    updateTransientActions();
    getBuildersList().setOwner(this);
    getPublishersList().setOwner(this);
    getBuildWrappersList().setOwner(this);

    initRepos();
}
 
Example 3
@Before
public void before() {
    MockitoAnnotations.initMocks(this);

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

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

    response = mockRelationshipResponse();
}
 
Example 4
Source Project: bdf3   File: AbstractNewGeneratorPolicy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Object entity, Field field) {
	field.setAccessible(true);
	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
@Override
public T get(ID id, Object... uriVariables) throws FirebaseRepositoryException {
    ReflectionUtils.makeAccessible(documentId);

    HttpEntity httpEntity = HttpEntityBuilder.create(firebaseObjectMapper, firebaseApplicationService).build();
    T response = restTemplate.exchange(getDocumentPath(id), 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()) {
		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);
}
 
Example 7
Source Project: JetfireCloud   File: PrivateHelper.java    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.makeAccessible(signingKeyField);
    ReflectionUtils.setField(signingKeyField, instance, value);

}
 
Example 8
Source Project: Milkomeda   File: ReflectUtil.java    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) {
        return;
    }
    ReflectionUtils.setField(fieldBundle.getKey(), fieldBundle.getValue(), value);
}
 
Example 9
Source Project: mojito   File: RawDocument.java    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");
    ReflectionUtils.makeAccessible(inputURIField);

    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: ConsulUtils.java    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.makeAccessible(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);
		field.setAccessible(true);
		int modifiers = field.getModifiers();
		Field modifierField = field.getClass().getDeclaredField("modifiers");
		modifiers = modifiers & ~Modifier.FINAL;
		modifierField.setAccessible(true);
		modifierField.setInt(field, modifiers);
		ReflectionUtils.setField(field, instance, value);
	}
	catch (ReflectiveOperationException e) {
		throw new IllegalArgumentException(e);
	}
}
 
Example 12
@Before
public void setup() throws IllegalArgumentException, IllegalAccessException {
	MockitoAnnotations.initMocks(this);
	cfCertTruster = new CloudFoundryCertificateTruster();
	Field envField = ReflectionUtils.findField(CloudFoundryCertificateTruster.class, "env");
	ReflectionUtils.makeAccessible(envField);
	ReflectionUtils.setField(envField, cfCertTruster, env);
	Field sslCertTrusterField = ReflectionUtils.findField(CloudFoundryCertificateTruster.class,
			"sslCertificateTruster");
	ReflectionUtils.makeAccessible(sslCertTrusterField);
	ReflectionUtils.setField(sslCertTrusterField, cfCertTruster, sslCertTruster);
}
 
Example 13
@Before
public void before() throws InvalidParameterException {
    MockitoAnnotations.initMocks(this);

    governanceEngine = new GovernanceEngine(SERVER_NAME, SERVER_URL);
    Field connectorField = ReflectionUtils.findField(GovernanceEngine.class, "clientConnector");
    if (connectorField != null) {
        connectorField.setAccessible(true);
        ReflectionUtils.setField(connectorField, governanceEngine, connector);
        connectorField.setAccessible(false);
    }
}
 
Example 14
public ClientHttpResponse execute() throws IOException {
    ClientHttpResponse response = delegate.execute();
    if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        logger.info("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 {
            logger.info("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("org.springframework.social.oauth2.OAuth2RequestInterceptor")) {
                    Field field = ReflectionUtils.findField(interceptor.getClass(), "accessToken");
                    field.setAccessible(true);
                    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
@Before
public void setUp() {
	beanFactory = mock(DefaultListableBeanFactory.class);
	sentinelProperties = mock(SentinelProperties.class);
	sentinelHealthIndicator = new SentinelHealthIndicator(beanFactory,
			sentinelProperties);

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

	heartbeatSender = mock(HeartbeatSender.class);
	Field heartbeatSenderField = ReflectionUtils
			.findField(HeartbeatSenderProvider.class, "heartbeatSender");
	heartbeatSenderField.setAccessible(true);
	ReflectionUtils.setField(heartbeatSenderField, null, heartbeatSender);
}
 
Example 16
Source Project: egeria   File: GlossaryViewClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception{
    MockitoAnnotations.initMocks(this);

    underTest = new GlossaryViewClient(SERVER_NAME, SERVER_PLATFORM_URL, USER_ID, USER_PASSWORD);

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

    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)) {
    return;
  }
  Field field = ReflectionUtils.findField(VertxImpl.class, "eventLoopThreadFactory");
  field.setAccessible(true);
  VertxThreadFactory eventLoopThreadFactory = (VertxThreadFactory) ReflectionUtils.getField(field, vertx);

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

  String prefix = (String) ReflectionUtils.getField(field, eventLoopThreadFactory);
  ReflectionUtils.setField(field, eventLoopThreadFactory, name + "-" + prefix);
}
 
Example 18
Source Project: didi-eureka-server   File: CloudJacksonJson.java    License: MIT License 4 votes vote down vote up
void setField(String name, Object value) {
	Field field = ReflectionUtils.findField(EurekaJacksonCodec.class, name);
	ReflectionUtils.makeAccessible(field);
	ReflectionUtils.setField(field, this, value);
}
 
Example 19
Source Project: DesignPatterns   File: ValidatorUtil.java    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);
    ReflectionUtils.makeAccessible(dataField);
    ReflectionUtils.setField(dataField,detail,null);
}
 
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) {
	makeAccessible(field);
	ReflectionUtils.setField(field, target, value);
}