Java Code Examples for org.springframework.util.ReflectionUtils#makeAccessible()
The following examples show how to use
org.springframework.util.ReflectionUtils#makeAccessible() .
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: SpringNettyConfiguration.java From spring-boot-netty with MIT License | 7 votes |
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
Source File: MybatisReflectionEntityInformation.java From spring-data-mybatis with Apache License 2.0 | 6 votes |
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 3
Source File: SolrClientUtils.java From dubbox with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: WebFluxConfigurationSupportTests.java From java-technology-stack with MIT License | 6 votes |
@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 5
Source File: WebFluxConfigurationSupportTests.java From spring-analysis-note with MIT License | 6 votes |
@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 6
Source File: ReflectiveConstructorExecutor.java From java-technology-stack with MIT License | 6 votes |
@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 7
Source File: MapperCacheDisabler.java From Mapper with MIT License | 6 votes |
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 8
Source File: TemporaryMockOverride.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
@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 9
Source File: DirectFieldAccessor.java From jdal with Apache License 2.0 | 5 votes |
@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 10
Source File: RuntimeTestWalker.java From spring4-understanding with Apache License 2.0 | 5 votes |
public RuntimeTestWalker(ShadowMatch shadowMatch) { try { ReflectionUtils.makeAccessible(residualTestField); this.runtimeTest = (Test) residualTestField.get(shadowMatch); } catch (IllegalAccessException ex) { throw new IllegalStateException(ex); } }
Example 11
Source File: RuntimeTestWalker.java From spring-analysis-note with MIT License | 5 votes |
protected int getVarType(ReflectionVar v) { try { ReflectionUtils.makeAccessible(varTypeField); return (Integer) varTypeField.get(v); } catch (IllegalAccessException ex) { throw new IllegalStateException(ex); } }
Example 12
Source File: ScheduleRunnable.java From Ffast-Java with MIT License | 5 votes |
@Override public void run() { try { ReflectionUtils.makeAccessible(method); if (StringUtils.isNotBlank(params)) { method.invoke(target, params); } else { method.invoke(target); } } catch (Exception e) { // 执行定时任务失败 } }
Example 13
Source File: FunctionalInstallerListener.java From spring-init with Apache License 2.0 | 5 votes |
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 14
Source File: ScheduleRunnable.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
@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 15
Source File: ReflectionTestUtils.java From java-technology-stack with MIT License | 5 votes |
/** * 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 "name" or * "setName" 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 16
Source File: JmsListenerAnnotationBeanPostProcessorTests.java From spring-analysis-note with MIT License | 5 votes |
@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
Source File: ContentDispositionTests.java From java-technology-stack with MIT License | 5 votes |
@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 File: RouteInformationProvider.java From gocd with Apache License 2.0 | 4 votes |
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
Source File: FeignOkHttpConfigurationTests.java From spring-cloud-openfeign with Apache License 2.0 | 4 votes |
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
Source File: UrlTagTests.java From spring4-understanding with Apache License 2.0 | 4 votes |
private String invokeCreateUrl(UrlTag tag) { Method createUrl = ReflectionUtils.findMethod(tag.getClass(), "createUrl"); ReflectionUtils.makeAccessible(createUrl); return (String) ReflectionUtils.invokeMethod(createUrl, tag); }