org.springframework.util.ReflectionUtils Java Examples
The following examples show how to use
org.springframework.util.ReflectionUtils.
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: CosmosEntityInformation.java From spring-data-cosmosdb with MIT License | 7 votes |
private Field getIdField(Class<?> domainType) { final Field idField; final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(domainType, Id.class); if (fields.isEmpty()) { idField = ReflectionUtils.findField(getJavaType(), Constants.ID_PROPERTY_NAME); } else if (fields.size() == 1) { idField = fields.get(0); } else { throw new IllegalArgumentException("only one field with @Id annotation!"); } if (idField == null) { throw new IllegalArgumentException("domain should contain @Id field or field named id"); } else if (idField.getType() != String.class && idField.getType() != Integer.class && idField.getType() != int.class) { throw new IllegalArgumentException("type of id field must be String or Integer"); } return idField; }
Example #2
Source File: HibernateTemplate.java From java-technology-stack with MIT License | 6 votes |
@Deprecated @Override @SuppressWarnings({"rawtypes", "deprecation"}) public Iterator<?> iterate(final String queryString, @Nullable final Object... values) throws DataAccessException { return nonNull(executeWithNativeSession((HibernateCallback<Iterator<?>>) session -> { org.hibernate.Query queryObject = queryObject( ReflectionUtils.invokeMethod(createQueryMethod, session, queryString)); prepareQuery(queryObject); if (values != null) { for (int i = 0; i < values.length; i++) { queryObject.setParameter(i, values[i]); } } return queryObject.iterate(); })); }
Example #3
Source File: ApacheDubboServiceBeanPostProcessor.java From soul with Apache License 2.0 | 6 votes |
private void handler(final ServiceBean serviceBean) { Class<?> clazz = serviceBean.getRef().getClass(); if (ClassUtils.isCglibProxyClass(clazz)) { String superClassName = clazz.getGenericSuperclass().getTypeName(); try { clazz = Class.forName(superClassName); } catch (ClassNotFoundException e) { log.error(String.format("class not found: %s", superClassName)); return; } } final Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(clazz); for (Method method : methods) { SoulDubboClient soulDubboClient = method.getAnnotation(SoulDubboClient.class); if (Objects.nonNull(soulDubboClient)) { post(buildJsonParams(serviceBean, soulDubboClient, method)); } } }
Example #4
Source File: TestContextManager.java From spring-analysis-note with MIT License | 6 votes |
/** * Hook for pre-processing a test class <em>before</em> execution of any * tests within the class. Should be called prior to any framework-specific * <em>before class methods</em> (e.g., methods annotated with JUnit 4's * {@link org.junit.BeforeClass @BeforeClass}). * <p>An attempt will be made to give each registered * {@link TestExecutionListener} a chance to pre-process the test class * execution. If a listener throws an exception, however, the remaining * registered listeners will <strong>not</strong> be called. * @throws Exception if a registered TestExecutionListener throws an * exception * @since 3.0 * @see #getTestExecutionListeners() */ public void beforeTestClass() throws Exception { Class<?> testClass = getTestContext().getTestClass(); if (logger.isTraceEnabled()) { logger.trace("beforeTestClass(): class [" + testClass.getName() + "]"); } getTestContext().updateState(null, null, null); for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) { try { testExecutionListener.beforeTestClass(getTestContext()); } catch (Throwable ex) { logException(ex, "beforeTestClass", testExecutionListener, testClass); ReflectionUtils.rethrowException(ex); } } }
Example #5
Source File: ModuleMappingLoader.java From mPaaS with Apache License 2.0 | 6 votes |
/** * 构建单个maping信息到map中 * * @param resultMap * @param key * @param value */ default void buildMapingInfo(Map<String, ModuleMappingInfo> resultMap, String key, String value) { if (!StringUtils.isEmpty(key) && key.startsWith(SVR_PREFIX) && !StringUtils.isEmpty(value)) { String method = "set" + StringHelper.toFirstUpperCase(key.substring(key.lastIndexOf(NamingConstant.DOT) + 1)); key = key.substring(SVR_PREFIX.length(), key.lastIndexOf(NamingConstant.DOT)); ModuleMappingInfo info = resultMap.get(key); if (info == null) { info = new ModuleMappingInfo(); resultMap.put(key, info); } Method methodObj = ReflectionUtils.findMethod(info.getClass(), method, String.class); if (methodObj != null) { ReflectionUtils.invokeMethod(methodObj, info, value); } } }
Example #6
Source File: CustomCollectionEditor.java From java-technology-stack with MIT License | 6 votes |
/** * Create a Collection of the given type, with the given * initial capacity (if supported by the Collection type). * @param collectionType a sub-interface of Collection * @param initialCapacity the initial capacity * @return the new Collection instance */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Collection<Object> createCollection(Class<? extends Collection> collectionType, int initialCapacity) { if (!collectionType.isInterface()) { try { return ReflectionUtils.accessibleConstructor(collectionType).newInstance(); } catch (Throwable ex) { throw new IllegalArgumentException( "Could not instantiate collection class: " + collectionType.getName(), ex); } } else if (List.class == collectionType) { return new ArrayList<>(initialCapacity); } else if (SortedSet.class == collectionType) { return new TreeSet<>(); } else { return new LinkedHashSet<>(initialCapacity); } }
Example #7
Source File: Jaxb2CollectionHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
/** * Create a Collection of the given type, with the given initial capacity * (if supported by the Collection type). * @param collectionClass the type of Collection to instantiate * @return the created Collection instance */ @SuppressWarnings("unchecked") protected T createCollection(Class<?> collectionClass) { if (!collectionClass.isInterface()) { try { return (T) ReflectionUtils.accessibleConstructor(collectionClass).newInstance(); } catch (Throwable ex) { throw new IllegalArgumentException( "Could not instantiate collection class: " + collectionClass.getName(), ex); } } else if (List.class == collectionClass) { return (T) new ArrayList(); } else if (SortedSet.class == collectionClass) { return (T) new TreeSet(); } else { return (T) new LinkedHashSet(); } }
Example #8
Source File: Property.java From java-technology-stack with MIT License | 6 votes |
@Nullable private Field getField() { String name = getName(); if (!StringUtils.hasLength(name)) { return null; } Field field = null; Class<?> declaringClass = declaringClass(); if (declaringClass != null) { field = ReflectionUtils.findField(declaringClass, name); if (field == null) { // Same lenient fallback checking as in CachedIntrospectionResults... field = ReflectionUtils.findField(declaringClass, StringUtils.uncapitalize(name)); if (field == null) { field = ReflectionUtils.findField(declaringClass, StringUtils.capitalize(name)); } } } return field; }
Example #9
Source File: MvcUriComponentsBuilder.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) { if (getControllerMethod.equals(method)) { return this.controllerMethod; } else if (getArgumentValues.equals(method)) { return this.argumentValues; } else if (getControllerType.equals(method)) { return this.controllerType; } else if (ReflectionUtils.isObjectMethod(method)) { return ReflectionUtils.invokeMethod(method, obj, args); } else { this.controllerMethod = method; this.argumentValues = args; Class<?> returnType = method.getReturnType(); return (void.class == returnType ? null : returnType.cast(initProxy(returnType, this))); } }
Example #10
Source File: SimpleInstantiationStrategy.java From spring-analysis-note with MIT License | 6 votes |
@Override public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner, final Constructor<?> ctor, Object... args) { if (!bd.hasMethodOverrides()) { if (System.getSecurityManager() != null) { // use own privileged to change accessibility (when security is on) AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(ctor); return null; }); } return BeanUtils.instantiateClass(ctor, args); } else { return instantiateWithMethodInjection(bd, beanName, owner, ctor, args); } }
Example #11
Source File: SourceResolverServiceImpl.java From JuniperBot with GNU General Public License v3.0 | 6 votes |
@Override public Guild getGuild(GenericEvent event) { if (event == null) { return null; } Class<? extends GenericEvent> clazz = event.getClass(); Method method; if (!guildAccessors.containsKey(clazz)) { method = ReflectionUtils.findMethod(clazz, "getGuild"); guildAccessors.put(clazz, method); } else { method = guildAccessors.get(clazz); } if (method != null) { try { Object result = ReflectionUtils.invokeMethod(method, event); if (result instanceof Guild) { return (Guild) result; } } catch (Exception e) { // we don't care } } return null; }
Example #12
Source File: LazyTraceThreadPoolTaskScheduler.java From elasticactors with Apache License 2.0 | 6 votes |
LazyTraceThreadPoolTaskScheduler(ThreadPoolTaskScheduler delegate) { this.delegate = delegate; this.initializeExecutor = ReflectionUtils .findMethod(ThreadPoolTaskScheduler.class, "initializeExecutor", null); makeAccessibleIfNotNull(this.initializeExecutor); this.createExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "createExecutor", null); makeAccessibleIfNotNull(this.createExecutor); this.cancelRemainingTask = ReflectionUtils .findMethod(ThreadPoolTaskScheduler.class, "cancelRemainingTask", null); makeAccessibleIfNotNull(this.cancelRemainingTask); this.nextThreadName = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "nextThreadName", null); makeAccessibleIfNotNull(this.nextThreadName); this.getDefaultThreadNamePrefix = ReflectionUtils.findMethod( CustomizableThreadCreator.class, "getDefaultThreadNamePrefix", null); makeAccessibleIfNotNull(this.getDefaultThreadNamePrefix); }
Example #13
Source File: TaskManager.java From Taroco-Scheduler with GNU General Public License v2.0 | 6 votes |
/** * 封装ScheduledMethodRunnable对象 */ private ScheduledMethodRunnable buildScheduledRunnable(Object bean, String targetMethod, String params, String extKeySuffix, String scheduleKey) { Method method; Class<?> clazz; if (AopUtils.isAopProxy(bean)) { clazz = AopProxyUtils.ultimateTargetClass(bean); } else { clazz = bean.getClass(); } if (params != null) { method = ReflectionUtils.findMethod(clazz, targetMethod, String.class); } else { method = ReflectionUtils.findMethod(clazz, targetMethod); } if (ObjectUtils.isEmpty(method)) { zkClient.getTaskGenerator().getScheduleTask().saveRunningInfo(scheduleKey, ScheduleServer.getInstance().getUuid(), "method not found"); log.error("启动动态任务失败: {}, 失败原因: {}", scheduleKey, "method not found"); return null; } return new ScheduledMethodRunnable(bean, method, params, extKeySuffix); }
Example #14
Source File: NotificationSubjectHandlerMethodArgumentResolverTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void resolveArgument_wrongMessageType_reportsErrors() throws Exception { // Arrange NotificationSubjectHandlerMethodArgumentResolver resolver = new NotificationSubjectHandlerMethodArgumentResolver(); byte[] subscriptionRequestJsonContent = FileCopyUtils.copyToByteArray( new ClassPathResource("subscriptionConfirmation.json", getClass()) .getInputStream()); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.setContent(subscriptionRequestJsonContent); MethodParameter methodParameter = new MethodParameter( ReflectionUtils.findMethod(NotificationMethods.class, "subscriptionMethod", NotificationStatus.class), 0); // Assert assertThatThrownBy(() -> resolver.resolveArgument(methodParameter, null, new ServletWebRequest(servletRequest), null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "@NotificationMessage annotated parameters are only allowed"); }
Example #15
Source File: AnnotationTypeMapping.java From spring-analysis-note with MIT License | 6 votes |
private void processAliases(int attributeIndex, List<Method> aliases) { int rootAttributeIndex = getFirstRootAttributeIndex(aliases); AnnotationTypeMapping mapping = this; while (mapping != null) { if (rootAttributeIndex != -1 && mapping != this.root) { for (int i = 0; i < mapping.attributes.size(); i++) { if (aliases.contains(mapping.attributes.get(i))) { mapping.aliasMappings[i] = rootAttributeIndex; } } } mapping.mirrorSets.updateFrom(aliases); mapping.claimedAliases.addAll(aliases); if (mapping.annotation != null) { int[] resolvedMirrors = mapping.mirrorSets.resolve(null, mapping.annotation, ReflectionUtils::invokeMethod); for (int i = 0; i < mapping.attributes.size(); i++) { if (aliases.contains(mapping.attributes.get(i))) { this.annotationValueMappings[attributeIndex] = resolvedMirrors[i]; this.annotationValueSource[attributeIndex] = mapping; } } } mapping = mapping.parent; } }
Example #16
Source File: RmiClientInterceptorUtils.java From spring-analysis-note with MIT License | 6 votes |
/** * Convert the given RemoteException that happened during remote access * to Spring's RemoteAccessException if the method signature does not * support RemoteException. Else, return the original RemoteException. * @param method the invoked method * @param ex the RemoteException that happened * @param isConnectFailure whether the given exception should be considered * a connect failure * @param serviceName the name of the service (for debugging purposes) * @return the exception to be thrown to the caller */ public static Exception convertRmiAccessException( Method method, RemoteException ex, boolean isConnectFailure, String serviceName) { if (logger.isDebugEnabled()) { logger.debug("Remote service [" + serviceName + "] threw exception", ex); } if (ReflectionUtils.declaresException(method, ex.getClass())) { return ex; } else { if (isConnectFailure) { return new RemoteConnectFailureException("Could not connect to remote service [" + serviceName + "]", ex); } else { return new RemoteAccessException("Could not access remote service [" + serviceName + "]", ex); } } }
Example #17
Source File: TestContextManager.java From spring-analysis-note with MIT License | 6 votes |
/** * Hook for preparing a test instance prior to execution of any individual * test methods, for example for injecting dependencies, etc. Should be * called immediately after instantiation of the test instance. * <p>The managed {@link TestContext} will be updated with the supplied * {@code testInstance}. * <p>An attempt will be made to give each registered * {@link TestExecutionListener} a chance to prepare the test instance. If a * listener throws an exception, however, the remaining registered listeners * will <strong>not</strong> be called. * @param testInstance the test instance to prepare (never {@code null}) * @throws Exception if a registered TestExecutionListener throws an exception * @see #getTestExecutionListeners() */ public void prepareTestInstance(Object testInstance) throws Exception { if (logger.isTraceEnabled()) { logger.trace("prepareTestInstance(): instance [" + testInstance + "]"); } getTestContext().updateState(testInstance, null, null); for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) { try { testExecutionListener.prepareTestInstance(getTestContext()); } catch (Throwable ex) { if (logger.isErrorEnabled()) { logger.error("Caught exception while allowing TestExecutionListener [" + testExecutionListener + "] to prepare test instance [" + testInstance + "]", ex); } ReflectionUtils.rethrowException(ex); } } }
Example #18
Source File: LazyTraceThreadPoolTaskScheduler.java From spring-cloud-sleuth with Apache License 2.0 | 6 votes |
LazyTraceThreadPoolTaskScheduler(BeanFactory beanFactory, ThreadPoolTaskScheduler delegate) { this.beanFactory = beanFactory; this.delegate = delegate; this.initializeExecutor = ReflectionUtils .findMethod(ThreadPoolTaskScheduler.class, "initializeExecutor", null); makeAccessibleIfNotNull(this.initializeExecutor); this.createExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "createExecutor", null); makeAccessibleIfNotNull(this.createExecutor); this.cancelRemainingTask = ReflectionUtils .findMethod(ThreadPoolTaskScheduler.class, "cancelRemainingTask", null); makeAccessibleIfNotNull(this.cancelRemainingTask); this.nextThreadName = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "nextThreadName", null); makeAccessibleIfNotNull(this.nextThreadName); this.getDefaultThreadNamePrefix = ReflectionUtils.findMethod( CustomizableThreadCreator.class, "getDefaultThreadNamePrefix", null); makeAccessibleIfNotNull(this.getDefaultThreadNamePrefix); }
Example #19
Source File: ConfigurationClassEnhancer.java From java-technology-stack with MIT License | 5 votes |
private ConfigurableBeanFactory getBeanFactory(Object enhancedConfigInstance) { Field field = ReflectionUtils.findField(enhancedConfigInstance.getClass(), BEAN_FACTORY_FIELD); Assert.state(field != null, "Unable to find generated bean factory field"); Object beanFactory = ReflectionUtils.getField(field, enhancedConfigInstance); Assert.state(beanFactory != null, "BeanFactory has not been injected into @Configuration class"); Assert.state(beanFactory instanceof ConfigurableBeanFactory, "Injected BeanFactory is not a ConfigurableBeanFactory"); return (ConfigurableBeanFactory) beanFactory; }
Example #20
Source File: SentinelFeign.java From spring-cloud-alibaba with Apache License 2.0 | 5 votes |
private Object getFieldValue(Object instance, String fieldName) { Field field = ReflectionUtils.findField(instance.getClass(), fieldName); field.setAccessible(true); try { return field.get(instance); } catch (IllegalAccessException e) { // ignore } return null; }
Example #21
Source File: QuerydslJdbcRepositoryFactory.java From infobip-spring-data-querydsl with Apache License 2.0 | 5 votes |
private RelationalPathBase<?> getRelationalPathBase(Class<?> queryClass) { String fieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, queryClass.getSimpleName().substring(1)); Field field = ReflectionUtils.findField(queryClass, fieldName); if (field == null) { throw new IllegalArgumentException("Did not find a static field of the same type in " + queryClass); } return (RelationalPathBase<?>) ReflectionUtils.getField(field, null); }
Example #22
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 #23
Source File: JCacheInterceptorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void noCacheCouldBeResolved() { JCacheInterceptor interceptor = createInterceptor(createOperationSource( cacheManager, new NamedCacheResolver(cacheManager), // Returns empty list defaultExceptionCacheResolver, defaultKeyGenerator)); AnnotatedJCacheableService service = new AnnotatedJCacheableService(cacheManager.getCache("default")); Method m = ReflectionUtils.findMethod(AnnotatedJCacheableService.class, "cache", String.class); assertThatIllegalStateException().isThrownBy(() -> interceptor.execute(dummyInvoker, service, m, new Object[] {"myId"})) .withMessageContaining("Cache could not have been resolved for"); }
Example #24
Source File: MethodInvokerConfig.java From rice with Educational Community License v2.0 | 5 votes |
/** * Finds the method on the target class that matches the target name and * returns the declared parameter types * * @return method parameter types */ protected Class[] getMethodArgumentTypes() { if (StringUtils.isNotBlank(staticMethod)) { int lastDotIndex = this.staticMethod.lastIndexOf('.'); if (lastDotIndex == -1 || lastDotIndex == this.staticMethod.length()) { throw new IllegalArgumentException("staticMethod must be a fully qualified class plus method name: " + "e.g. 'example.MyExampleClass.myExampleMethod'"); } String className = this.staticMethod.substring(0, lastDotIndex); String methodName = this.staticMethod.substring(lastDotIndex + 1); try { setTargetClass(resolveClassName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to get class for name: " + className); } setTargetMethod(methodName); } Method matchingCandidate = findMatchingMethod(); if (matchingCandidate != null) { return matchingCandidate.getParameterTypes(); } Method[] candidates = ReflectionUtils.getAllDeclaredMethods(getTargetClass()); for (Method candidate : candidates) { if (candidate.getName().equals(getTargetMethod())) { return candidate.getParameterTypes(); } } return null; }
Example #25
Source File: ScheduleRunnable.java From mysiteforme 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) { throw new MyException("执行定时任务失败", e); } }
Example #26
Source File: DbBackedBuild.java From DotCi with MIT License | 5 votes |
public String getState() { String stateName = null; try { final Field field = Run.class.getDeclaredField("state"); field.setAccessible(true); stateName = ReflectionUtils.getField(field, this).toString(); } catch (final Exception e) { throw new RuntimeException(e); } return stateName; }
Example #27
Source File: ApplicationListenerMethodAdapterTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void invokeListenerWithWrongGenericPayload() { Method method = ReflectionUtils.findMethod (SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class); EntityWrapper<Integer> payload = new EntityWrapper<>(123); invokeListener(method, new PayloadApplicationEvent<>(this, payload)); verify(this.sampleEvents, times(0)).handleGenericStringPayload(any()); }
Example #28
Source File: AnnotatedElementKeyTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void equals() { Method m = ReflectionUtils.findMethod(getClass(), name.getMethodName()); AnnotatedElementKey first = new AnnotatedElementKey(m, getClass()); AnnotatedElementKey second = new AnnotatedElementKey(m, getClass()); assertKeyEquals(first, second); }
Example #29
Source File: ApplicationListenerMethodAdapterTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void invokeListenerRuntimeException() { Method method = ReflectionUtils.findMethod( SampleEvents.class, "generateRuntimeException", GenericTestEvent.class); GenericTestEvent<String> event = createGenericTestEvent("fail"); assertThatIllegalStateException().isThrownBy(() -> invokeListener(method, event)) .withMessageContaining("Test exception") .withNoCause(); }
Example #30
Source File: QuickPerfProxyBeanPostProcessor.java From quickperf with Apache License 2.0 | 5 votes |
@Override public Object invoke(final MethodInvocation invocation) throws Throwable { Method proxyMethod = ReflectionUtils.findMethod( this.datasourceProxy.getClass() , invocation.getMethod().getName()); if (proxyMethod != null) { return proxyMethod.invoke(this.datasourceProxy, invocation.getArguments()); } return invocation.proceed(); }