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 File: AssetCatalogRelationshipServiceTest.java From egeria with Apache License 2.0 | 6 votes |
@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 2
Source File: DynamicSubProject.java From DotCi with MIT License | 6 votes |
@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
Source File: BeanUtils.java From spring-content with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: CloudFoundryCertificateTrusterTest.java From cloudfoundry-certificate-truster with Apache License 2.0 | 5 votes |
@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 5
Source File: VertxUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
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 6
Source File: GlossaryViewClientTest.java From egeria with Apache License 2.0 | 5 votes |
@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 7
Source File: SentinelHealthIndicatorTests.java From spring-cloud-alibaba with Apache License 2.0 | 5 votes |
@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 8
Source File: TokenRefreshingClientHttpRequestFactory.java From google-plus-java-api with Apache License 2.0 | 5 votes |
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 9
Source File: GovernanceEngineClientTest.java From egeria with Apache License 2.0 | 5 votes |
@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 10
Source File: StateMachineTests.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
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 11
Source File: ConsulUtils.java From cloudbreak with Apache License 2.0 | 5 votes |
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 12
Source File: RawDocument.java From mojito with Apache License 2.0 | 5 votes |
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 13
Source File: ReflectUtil.java From Milkomeda with MIT License | 5 votes |
/** * 设置属性路径值 * @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 14
Source File: PrivateHelper.java From JetfireCloud with Apache License 2.0 | 5 votes |
/** * @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 15
Source File: ReflectionTestUtils.java From spring-analysis-note with MIT License | 5 votes |
/** * 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 16
Source File: DefaultFirebaseRealtimeDatabaseRepository.java From spring-boot-starter-data-firebase with MIT License | 5 votes |
@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 17
Source File: AbstractNewGeneratorPolicy.java From bdf3 with Apache License 2.0 | 5 votes |
@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 18
Source File: CloudJacksonJson.java From didi-eureka-server with MIT License | 4 votes |
void setField(String name, Object value) { Field field = ReflectionUtils.findField(EurekaJacksonCodec.class, name); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, this, value); }
Example 19
Source File: ValidatorUtil.java From DesignPatterns with Apache License 2.0 | 4 votes |
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
Source File: ReflectUtil.java From mica with GNU Lesser General Public License v3.0 | 2 votes |
/** * 重写 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); }