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

The following examples show how to use org.springframework.util.ReflectionUtils#makeAccessible() . 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
private List<OnDisconnectMethodInvoker> buildDisconnectMethodInvokers(final String serverName, final Map<String, List<Method>> disconnectHandlers,
                                                                      final Collection<NettyOnDisconnectParameterResolver> disconnectParameterResolvers) {

    final List<Method> onDisconnect = disconnectHandlers.getOrDefault(serverName, new ArrayList<>());
    final List<OnDisconnectMethodInvoker> result = new ArrayList<>();
    for (final Method method : onDisconnect) {
        final List<NettyOnDisconnectParameterResolver> resolvers =
                buildMethodParameterResolvers(method, disconnectParameterResolvers);

        ReflectionUtils.makeAccessible(method);

        final Class<?> declaringClass = method.getDeclaringClass();
        final Object bean = beanFactory.getBean(declaringClass);
        final OnDisconnectMethodInvoker invoker = new OnDisconnectMethodInvoker(bean, method, resolvers);
        result.add(invoker);
    }

    return result;
}
 
Example 2
@Override protected void after()
{
    // For all objects that have been tampered with, we'll revert them to their original state.
    for (int i = pristineFieldValues.size() - 1; i >= 0; i-- )
    {
        FieldValueOverride override = pristineFieldValues.get(i);
        
        if (log.isDebugEnabled())
        {
            log.debug("Reverting mocked field '" + override.fieldName + "' on object " + override.objectContainingField + " to original value '" + override.fieldPristineValue + "'");
        }
        
        // Hack into the Java field object
        Field f = ReflectionUtils.findField(override.objectContainingField.getClass(), override.fieldName);
        ReflectionUtils.makeAccessible(f);
        // and revert its value.
        ReflectionUtils.setField(f, override.objectContainingField, override.fieldPristineValue);
    }
}
 
Example 3
Source Project: Mapper   File: MapperCacheDisabler.java    License: MIT License 6 votes vote down vote up
private void removeEntityHelperCache(Class<?> entityHelper) {
    try {
        Field cacheField = ReflectionUtils.findField(entityHelper, "entityTableMap");
        if (cacheField != null) {
            ReflectionUtils.makeAccessible(cacheField);
            Map cache = (Map) ReflectionUtils.getField(cacheField, null);
            //如果使用了 Devtools,这里获取的就是当前的 RestartClassLoader
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            for (Object key : new ArrayList(cache.keySet())) {
                Class entityClass = (Class) key;
                //清理老的ClassLoader缓存的数据,避免测试环境溢出
                if (!entityClass.getClassLoader().equals(classLoader)) {
                    cache.remove(entityClass);
                }
            }
            logger.info("Clear EntityHelper entityTableMap cache.");
        }
    } catch (Exception ex) {
        logger.warn("Failed to disable Mapper MsUtil cache. ClassCastExceptions may occur", ex);
    }
}
 
Example 4
@Override
public TypedValue execute(EvaluationContext context, Object... arguments) throws AccessException {
	try {
		ReflectionHelper.convertArguments(
				context.getTypeConverter(), arguments, this.ctor, this.varargsPosition);
		if (this.ctor.isVarArgs()) {
			arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(
					this.ctor.getParameterTypes(), arguments);
		}
		ReflectionUtils.makeAccessible(this.ctor);
		return new TypedValue(this.ctor.newInstance(arguments));
	}
	catch (Exception ex) {
		throw new AccessException("Problem invoking constructor: " + this.ctor, ex);
	}
}
 
Example 5
public MybatisReflectionEntityInformation(Class<T> domainClass) {
	super(domainClass);

	IdClass idClass = domainClass.getAnnotation(IdClass.class);
	if (null != idClass) {
		this.idClass = idClass.value();
	}
	else {
		for (Class<? extends Annotation> annotation : MybatisPersistentPropertyImpl.ID_ANNOTATIONS) {
			AnnotationDetectionFieldCallback callback = new AnnotationDetectionFieldCallback(
					annotation);
			ReflectionUtils.doWithFields(domainClass, callback);

			try {
				this.field = callback.getRequiredField();
			}
			catch (IllegalStateException o_O) {

			}
			if (null != this.field) {
				ReflectionUtils.makeAccessible(this.field);
				break;
			}
		}
	}
}
 
Example 6
@Test
public void customPathMatchConfig() {
	ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertFalse(matchOptionalTrailingSlash);

	Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
	assertEquals(1, map.size());
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			map.keySet().iterator().next().getPatternsCondition().getPatterns());
}
 
Example 7
@Test
public void customPathMatchConfig() {
	ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertFalse(matchOptionalTrailingSlash);

	Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
	assertEquals(1, map.size());
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			map.keySet().iterator().next().getPatternsCondition().getPatterns());
}
 
Example 8
Source Project: dubbox   File: SolrClientUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Solr property names do not match the getters/setters used for them. Check
 * on any write method, try to find the according property and set the value
 * for it. Will ignore all other, and nested properties
 * 
 * @param source
 * @param target
 */
private static void copyProperties(SolrClient source, SolrClient target) {
	BeanWrapperImpl wrapperImpl = new BeanWrapperImpl(source);
	for (PropertyDescriptor pd : wrapperImpl.getPropertyDescriptors()) {
		Method writer = pd.getWriteMethod();
		if (writer != null) {
			try {
				Field property = ReflectionUtils.findField(source.getClass(), pd.getName());
				if (property != null) {
					ReflectionUtils.makeAccessible(property);
					Object o = ReflectionUtils.getField(property, source);
					if (o != null) {
						writer.invoke(target, o);
					}
				}
			} catch (Exception e) {
				logger.warn("Could not copy property value for: " + pd.getName(), e);
			}
		}
	}
}
 
Example 9
Source Project: Ffast-Java   File: ScheduleRunnable.java    License: MIT License 5 votes vote down vote up
@Override
public void run() {
    try {
        ReflectionUtils.makeAccessible(method);
        if (StringUtils.isNotBlank(params)) {
            method.invoke(target, params);
        } else {
            method.invoke(target);
        }
    } catch (Exception e) {
        // 执行定时任务失败
    }
}
 
Example 10
/**
 * Invoke the setter method with the given {@code name} on the supplied
 * target object with the supplied {@code value}.
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> setter methods.
 * <p>In addition, this method supports JavaBean-style <em>property</em>
 * names. For example, if you wish to set the {@code name} property on the
 * target object, you may pass either &quot;name&quot; or
 * &quot;setName&quot; as the method name.
 * @param target the target object on which to invoke the specified setter
 * method
 * @param name the name of the setter method to invoke or the corresponding
 * property name
 * @param value the value to provide to the setter method
 * @param type the formal parameter type declared by the setter method
 * @see ReflectionUtils#findMethod(Class, String, Class[])
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 */
public static void invokeSetterMethod(Object target, String name, @Nullable Object value, @Nullable Class<?> type) {
	Assert.notNull(target, "Target object must not be null");
	Assert.hasText(name, "Method name must not be empty");
	Class<?>[] paramTypes = (type != null ? new Class<?>[] {type} : null);

	String setterMethodName = name;
	if (!name.startsWith(SETTER_PREFIX)) {
		setterMethodName = SETTER_PREFIX + StringUtils.capitalize(name);
	}

	Method method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
	if (method == null && !setterMethodName.equals(name)) {
		setterMethodName = name;
		method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
	}
	if (method == null) {
		throw new IllegalArgumentException(String.format(
				"Could not find setter method '%s' on %s with parameter type [%s]", setterMethodName,
				safeToString(target), type));
	}

	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Invoking setter method '%s' on %s with value [%s]", setterMethodName,
				safeToString(target), value));
	}

	ReflectionUtils.makeAccessible(method);
	ReflectionUtils.invokeMethod(method, target, value);
}
 
Example 11
public RuntimeTestWalker(ShadowMatch shadowMatch) {
	try {
		ReflectionUtils.makeAccessible(residualTestField);
		this.runtimeTest = (Test) residualTestField.get(shadowMatch);
	}
	catch (IllegalAccessException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 12
Source Project: jdal   File: DirectFieldAccessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object getPropertyValue(String propertyName) throws BeansException {
	Field field = this.fieldMap.get(propertyName);
	if (field == null) {
		throw new NotReadablePropertyException(
				this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist");
	}
	try {
		ReflectionUtils.makeAccessible(field);
		return field.get(this.target);
	}
	catch (IllegalAccessException ex) {
		throw new InvalidPropertyException(this.target.getClass(), propertyName, "Field is not accessible", ex);
	}
}
 
Example 13
Source Project: spring-analysis-note   File: RuntimeTestWalker.java    License: MIT License 5 votes vote down vote up
protected int getVarType(ReflectionVar v) {
	try {
		ReflectionUtils.makeAccessible(varTypeField);
		return (Integer) varTypeField.get(v);
	}
	catch (IllegalAccessException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 14
private void remove(SpringApplication application, Object source) {
	Field field = ReflectionUtils.findField(SpringApplication.class, "primarySources");
	ReflectionUtils.makeAccessible(field);
	@SuppressWarnings("unchecked")
	Set<Object> sources = (Set<Object>) ReflectionUtils.getField(field, application);
	sources.remove(source);
	application.getSources().remove(source);
}
 
Example 15
Source Project: FEBS-Cloud   File: ScheduleRunnable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        ReflectionUtils.makeAccessible(method);
        if (StringUtils.isNotBlank(params)) {
            method.invoke(target, params);
        } else {
            method.invoke(target);
        }
    } catch (Exception e) {
        log.error("执行定时任务失败", e);
    }
}
 
Example 16
@Test
public void sendToAnnotationFoundOnCglibProxy() throws Exception {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			Config.class, ProxyConfig.class, ClassProxyTestBean.class);
	try {
		JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class);
		assertEquals("one container should have been registered", 1, factory.getListenerContainers().size());

		JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint();
		assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass());
		MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint;
		assertTrue(AopUtils.isCglibProxy(methodEndpoint.getBean()));
		assertTrue(methodEndpoint.getBean() instanceof ClassProxyTestBean);
		assertEquals(ClassProxyTestBean.class.getMethod("handleIt", String.class, String.class),
				methodEndpoint.getMethod());
		assertEquals(ClassProxyTestBean.class.getMethod("handleIt", String.class, String.class),
				methodEndpoint.getMostSpecificMethod());

		Method method = ReflectionUtils.findMethod(endpoint.getClass(), "getDefaultResponseDestination");
		ReflectionUtils.makeAccessible(method);
		Object destination = ReflectionUtils.invokeMethod(method, endpoint);
		assertEquals("SendTo annotation not found on proxy", "foobar", destination);
	}
	finally {
		context.close();
	}
}
 
Example 17
@Test(expected = IllegalArgumentException.class)
public void encodeHeaderFieldParamInvalidCharset() {
	Method encode = ReflectionUtils.findMethod(ContentDisposition.class,
			"encodeHeaderFieldParam", String.class, Charset.class);
	ReflectionUtils.makeAccessible(encode);
	ReflectionUtils.invokeMethod(encode, null, "test", StandardCharsets.UTF_16);
}
 
Example 18
Source Project: gocd   File: RouteInformationProvider.java    License: Apache License 2.0 4 votes vote down vote up
private static <T> T getField(Object o, String fieldName) {
    Field field = ReflectionUtils.findField(o.getClass(), fieldName);
    ReflectionUtils.makeAccessible(field);
    return (T) ReflectionUtils.getField(field, o);
}
 
Example 19
protected <T> Object getField(Object target, String name) {
	Field field = ReflectionUtils.findField(target.getClass(), name);
	ReflectionUtils.makeAccessible(field);
	Object value = ReflectionUtils.getField(field, target);
	return value;
}
 
Example 20
private String invokeCreateUrl(UrlTag tag) {
	Method createUrl = ReflectionUtils.findMethod(tag.getClass(),
			"createUrl");
	ReflectionUtils.makeAccessible(createUrl);
	return (String) ReflectionUtils.invokeMethod(createUrl, tag);
}