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

The following examples show how to use org.springframework.util.ReflectionUtils#invokeMethod() . 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: LockingAndVersioningRestController.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = ENTITY_VERSION_MAPPING, method = RequestMethod.PUT)
public ResponseEntity<Resource<?>> version(RootResourceInformation repoInfo,
										   @PathVariable String repository,
										   @PathVariable String id,
										   @RequestBody VersionInfo info,
										   Principal principal,
										   PersistentEntityResourceAssembler assembler)
		throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {

	Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();

	domainObj = ReflectionUtils.invokeMethod(VERSION_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj, info);

	if (domainObj != null) {
		return new ResponseEntity(assembler.toResource(domainObj), HttpStatus.OK);
	} else {
		return ResponseEntity.status(HttpStatus.CONFLICT).build();
	}
}
 
Example 2
Source File: ShutdownApplicationListener.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> sources(ApplicationReadyEvent event) {
	Method method = ReflectionUtils.findMethod(SpringApplication.class,
			"getAllSources");
	if (method == null) {
		method = ReflectionUtils.findMethod(SpringApplication.class, "getSources");
	}
	ReflectionUtils.makeAccessible(method);
	@SuppressWarnings("unchecked")
	Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method,
			event.getSpringApplication());
	Set<Class<?>> result = new LinkedHashSet<>();
	for (Object object : objects) {
		if (object instanceof String) {
			object = ClassUtils.resolveClassName((String) object, null);
		}
		result.add((Class<?>) object);
	}
	return result;
}
 
Example 3
Source File: CachedMessageProducer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws JMSException {
	// It's a cached MessageProducer... reset properties only.
	if (this.originalDisableMessageID != null) {
		this.target.setDisableMessageID(this.originalDisableMessageID);
		this.originalDisableMessageID = null;
	}
	if (this.originalDisableMessageTimestamp != null) {
		this.target.setDisableMessageTimestamp(this.originalDisableMessageTimestamp);
		this.originalDisableMessageTimestamp = null;
	}
	if (this.originalDeliveryDelay != null) {
		ReflectionUtils.invokeMethod(setDeliveryDelayMethod, this.target, this.originalDeliveryDelay);
		this.originalDeliveryDelay = null;
	}
}
 
Example 4
Source File: AwsSecretsManagerBootstrapConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testWithStaticRegion() {
	String region = "us-east-2";
	AwsSecretsManagerProperties awsParamStoreProperties = new AwsSecretsManagerProperties();
	awsParamStoreProperties.setRegion(region);

	Method SMClientMethod = ReflectionUtils.findMethod(
			AwsSecretsManagerBootstrapConfiguration.class, "smClient",
			AwsSecretsManagerProperties.class);
	SMClientMethod.setAccessible(true);
	AWSSecretsManagerClient awsSimpleClient = (AWSSecretsManagerClient) ReflectionUtils
			.invokeMethod(SMClientMethod, bootstrapConfig, awsParamStoreProperties);

	Method signingRegionMethod = ReflectionUtils
			.findMethod(AmazonWebServiceClient.class, "getSigningRegion");
	signingRegionMethod.setAccessible(true);
	String signedRegion = (String) ReflectionUtils.invokeMethod(signingRegionMethod,
			awsSimpleClient);

	assertThat(signedRegion).isEqualTo(region);
}
 
Example 5
Source File: LockingAndVersioningRestController.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = ENTITY_LOCK_MAPPING, method = RequestMethod.DELETE)
public ResponseEntity<Resource<?>> unlock(RootResourceInformation repoInfo,
										  @PathVariable String repository,
										  @PathVariable String id, Principal principal)
		throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {

	Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();

	domainObj = ReflectionUtils.invokeMethod(UNLOCK_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj);

	if (domainObj != null) {
		return ResponseEntity.ok().build();
	} else {
		return ResponseEntity.status(HttpStatus.CONFLICT).build();
	}
}
 
Example 6
Source File: AnnotationBeanUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, @Nullable StringValueResolver valueResolver,
		String... excludedProperties) {

	Set<String> excluded = new HashSet<>(Arrays.asList(excludedProperties));
	Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	for (Method annotationProperty : annotationProperties) {
		String propertyName = annotationProperty.getName();
		if (!excluded.contains(propertyName) && bw.isWritableProperty(propertyName)) {
			Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
			if (valueResolver != null && value instanceof String) {
				value = valueResolver.resolveStringValue((String) value);
			}
			bw.setPropertyValue(propertyName, value);
		}
	}
}
 
Example 7
Source File: ReflectUtil.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 获取方法值
 * @param target        目标对象
 * @param methodName    方法名
 * @param paramTypes    参数类型列表
 * @param args          参数值
 * @param <T>           返回值类型
 * @return  返回值
 */
@SuppressWarnings("unchecked")
public static <T> T invokeMethod(Object target, String methodName, Class<?>[] paramTypes, Object... args) {
    Method method = ReflectionUtils.findMethod(target.getClass(), methodName, paramTypes);
    if (method == null) {
        return null;
    }
    ReflectionUtils.makeAccessible(method);
    return (T) ReflectionUtils.invokeMethod(method, target, args);
}
 
Example 8
Source File: SessionFactoryUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine the DataSource of the given SessionFactory.
 * @param sessionFactory the SessionFactory to check
 * @return the DataSource, or {@code null} if none found
 * @see ConnectionProvider
 */
@Nullable
public static DataSource getDataSource(SessionFactory sessionFactory) {
	Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
	if (getProperties != null) {
		Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
		if (props != null) {
			Object dataSourceValue = props.get(Environment.DATASOURCE);
			if (dataSourceValue instanceof DataSource) {
				return (DataSource) dataSourceValue;
			}
		}
	}
	if (sessionFactory instanceof SessionFactoryImplementor) {
		SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
		try {
			ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
			if (cp != null) {
				return cp.unwrap(DataSource.class);
			}
		}
		catch (UnknownServiceException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
			}
		}
	}
	return null;
}
 
Example 9
Source File: LazyTraceScheduledThreadPoolExecutor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable,
		RunnableScheduledFuture<V> task) {
	return (RunnableScheduledFuture<V>) ReflectionUtils.invokeMethod(
			this.decorateTaskRunnable, this.delegate,
			new TraceRunnable(tracing(), spanNamer(), runnable), task);
}
 
Example 10
Source File: EnumCodeList.java    From yyblog with MIT License 5 votes vote down vote up
public EnumCodeList(Class<? extends Enum<?>> enumClass) {
    Assert.isTrue(CodeListItem.class.isAssignableFrom(enumClass),
            "the given enumClass must implement " + CodeListItem.class);
    Map<String, String> codeList = new LinkedHashMap<String, String>();
    Method method = ReflectionUtils.findMethod(enumClass, "values");

    Enum<?>[] result = (Enum<?>[]) ReflectionUtils.invokeMethod(method,
            enumClass);
    for (Enum<?> e : result) {
        CodeListItem item = (CodeListItem) e;
        codeList.put(item.getCode(), item.getValue());
    }

    this.codeListMap = Collections.unmodifiableMap(codeList);
}
 
Example 11
Source File: StatusResultMatchersTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpStatusCodeResultMatchers() throws Exception {

	List<AssertionError> failures = new ArrayList<AssertionError>();

	for(HttpStatus status : HttpStatus.values()) {
		MockHttpServletResponse response = new MockHttpServletResponse();
		response.setStatus(status.value());
		MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response);
		try {
			Method method = getMethodForHttpStatus(status);
			ResultMatcher matcher = (ResultMatcher) ReflectionUtils.invokeMethod(method, this.matchers);
			try {
				matcher.match(mvcResult);
			}
			catch (AssertionError error) {
				failures.add(error);
			}
		}
		catch (Exception ex) {
			throw new Exception("Failed to obtain ResultMatcher for status " + status, ex);
		}
	}

	if (!failures.isEmpty()) {
		fail("Failed status codes: " + failures);
	}
}
 
Example 12
Source File: HTMLCompressingConfig.java    From wicket-spring-boot with Apache License 2.0 5 votes vote down vote up
private void setFeatureConfiguration(HtmlCompressor compressor) {
	for(Entry<String, Boolean> entrySet : props.getFeatures().entrySet()){
		Method method = null;
		String capitalizedKey = StringUtils.capitalize(entrySet.getKey());
		String methodname = "set" + capitalizedKey;
		try {
			method = compressor.getClass().getMethod(methodname, boolean.class);
			method.setAccessible(true);
			ReflectionUtils.invokeMethod(method, compressor, entrySet.getValue());
		} catch (Exception e) {
			logger.warn("failed to invoke method: {} with value {}. Exception: {}", methodname, entrySet.getValue(), e.getMessage());
		}
	}
}
 
Example 13
Source File: IdToEntityConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	Method finder = getFinder(targetType.getType());
	Object id = this.conversionService.convert(
			source, sourceType, TypeDescriptor.valueOf(finder.getParameterTypes()[0]));
	return ReflectionUtils.invokeMethod(finder, source, id);
}
 
Example 14
Source File: OAuth2SsoCustomConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	if (invocation.getMethod().getName().equals("init")) {
		Method method = ReflectionUtils.findMethod(WebSecurityConfigurerAdapter.class, "getHttp");
		ReflectionUtils.makeAccessible(method);
		HttpSecurity http = (HttpSecurity) ReflectionUtils.invokeMethod(method, invocation.getThis());
		this.configurer.configure(http);
	}
	return invocation.proceed();
}
 
Example 15
Source File: GenericJpaRepositoryImpl.java    From spring-data-jpa-extra with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public void toggleStatus(ID id) {
    if (isStatusAble && id != null) {
        Optional<T> target = findById(id);
        if (target.isPresent()) {
            Status status = (Status) ReflectionUtils.invokeMethod(statusReadMethod, target);
            if (status == Status.ENABLED || status == Status.DISABLED) {
                ReflectionUtils.invokeMethod(statusWriteMethod, target,
                        status == Status.DISABLED ? Status.ENABLED : Status.DISABLED);
                save(target.get());
            }
        }
    }
}
 
Example 16
Source File: LazyTraceScheduledThreadPoolExecutor.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeExecute(Thread t, Runnable r) {
    ReflectionUtils.invokeMethod(this.beforeExecute, this.delegate, t, TraceRunnable.wrap(r));
}
 
Example 17
Source File: MethodInvokeTypeProvider.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
    inputStream.defaultReadObject();
    Method method = ReflectionUtils.findMethod(this.provider.getType().getClass(), this.methodName);
    this.result = ReflectionUtils.invokeMethod(method, this.provider.getType());
}
 
Example 18
Source File: ReflectiveLoadTimeWeaver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void addTransformer(ClassFileTransformer transformer) {
	Assert.notNull(transformer, "Transformer must not be null");
	ReflectionUtils.invokeMethod(this.addTransformerMethod, this.classLoader, transformer);
}
 
Example 19
Source File: LazyTraceScheduledThreadPoolExecutor.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
@Override
public void afterExecute(Runnable r, Throwable t) {
    ReflectionUtils.invokeMethod(this.afterExecute, this.delegate, TraceRunnable.wrap(r), t);
}
 
Example 20
Source File: UrlTagTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private String invokeCreateUrl(UrlTag tag) {
	Method createUrl = ReflectionUtils.findMethod(tag.getClass(),
			"createUrl");
	ReflectionUtils.makeAccessible(createUrl);
	return (String) ReflectionUtils.invokeMethod(createUrl, tag);
}