下面列出了怎么用org.springframework.util.ReflectionUtils的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
/**
* 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);
}
}
}
/**
* 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);
}
}
/**
* 构建单个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);
}
}
}
@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;
}
@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();
}));
}
@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)));
}
}
@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);
}
}
/**
* 封装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);
}
@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");
}
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;
}
}
/**
* 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);
}
}
}
/**
* 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);
}
}
}
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);
}
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);
}
@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;
}
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));
}
}
}
/**
* 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();
}
}
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;
}
@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");
}
@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();
}
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;
}
boolean hasAnnotatedMethods(Class<?> clazz) {
final AtomicBoolean found = new AtomicBoolean(false);
ReflectionUtils.doWithMethods(clazz, (method -> {
if (found.get()) {
return;
}
Annotation annotation = AnnotationUtils.findAnnotation(method,
AnnotationMethodsResolver.this.annotationType);
if (annotation != null) {
found.set(true);
}
}));
return found.get();
}
@Override
protected void processMethod(Object bean, String beanName, Method method) {
ApolloJsonValue apolloJsonValue = AnnotationUtils.getAnnotation(method, ApolloJsonValue.class);
if (apolloJsonValue == null) {
return;
}
String placeHolder = apolloJsonValue.value();
Object propertyValue = placeholderHelper
.resolvePropertyValue(beanFactory, beanName, placeHolder);
// propertyValue will never be null, as @ApolloJsonValue will not allow that
if (!(propertyValue instanceof String)) {
return;
}
Type[] types = method.getGenericParameterTypes();
Preconditions.checkArgument(types.length == 1,
"Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
bean.getClass().getName(), method.getName(), method.getParameterTypes().length);
boolean accessible = method.isAccessible();
method.setAccessible(true);
ReflectionUtils.invokeMethod(method, bean, parseJsonValue((String)propertyValue, types[0]));
method.setAccessible(accessible);
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
Set<String> keys = placeholderHelper.extractPlaceholderKeys(placeHolder);
for (String key : keys) {
SpringValue springValue = new SpringValue(key, apolloJsonValue.value(), bean, beanName,
method, true);
springValueRegistry.register(beanFactory, key, springValue);
logger.debug("Monitoring {}", springValue);
}
}
}
@Test
public void invokeListenerWithGenericPayload() {
Method method = ReflectionUtils.findMethod(
SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
EntityWrapper<String> payload = new EntityWrapper<>("test");
invokeListener(method, new PayloadApplicationEvent<>(this, payload));
verify(this.sampleEvents, times(1)).handleGenericStringPayload(payload);
}
private void handleReferenceField(Object obj, Field field,
RpcReference reference) {
String microserviceName = reference.microserviceName();
microserviceName = resolver.resolveStringValue(microserviceName);
PojoReferenceMeta pojoReference = new PojoReferenceMeta();
pojoReference.setMicroserviceName(microserviceName);
pojoReference.setSchemaId(reference.schemaId());
pojoReference.setConsumerIntf(field.getType());
pojoReference.afterPropertiesSet();
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, obj, pojoReference.getProxy());
}
@Test
public void phaseAndClassesSet() {
Method m = ReflectionUtils.findMethod(SampleEvents.class, "phaseAndClassesSet");
assertPhase(m, TransactionPhase.AFTER_COMPLETION);
supportsEventType(true, m, createGenericEventType(String.class));
supportsEventType(true, m, createGenericEventType(Integer.class));
supportsEventType(false, m, createGenericEventType(Double.class));
}
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);
}
/**
* Identify a specific GlassFish thread pool to talk to.
* <p>The thread pool name matches the resource adapter name
* in default RAR deployment scenarios.
*/
public void setThreadPoolName(String threadPoolName) {
WorkManager wm = (WorkManager) ReflectionUtils.invokeMethod(this.getWorkManagerMethod, null, threadPoolName);
if (wm == null) {
throw new IllegalArgumentException("Specified thread pool name '" + threadPoolName +
"' does not correspond to an actual pool definition in GlassFish. Check your configuration!");
}
setWorkManager(wm);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
registerJobExecutionEventListener(bean);
if (bean instanceof AbstractStep) {
registerStepExecutionEventListener(bean);
if (bean instanceof TaskletStep) {
TaskletStep taskletStep = (TaskletStep) bean;
Tasklet tasklet = taskletStep.getTasklet();
registerChunkEventsListener(bean);
if (tasklet instanceof ChunkOrientedTasklet) {
Field chunkProviderField = ReflectionUtils
.findField(ChunkOrientedTasklet.class, "chunkProvider");
ReflectionUtils.makeAccessible(chunkProviderField);
SimpleChunkProvider chunkProvider = (SimpleChunkProvider) ReflectionUtils
.getField(chunkProviderField, tasklet);
Field chunkProcessorField = ReflectionUtils
.findField(ChunkOrientedTasklet.class, "chunkProcessor");
ReflectionUtils.makeAccessible(chunkProcessorField);
SimpleChunkProcessor chunkProcessor = (SimpleChunkProcessor) ReflectionUtils
.getField(chunkProcessorField, tasklet);
registerItemReadEvents(chunkProvider);
registerSkipEvents(chunkProvider);
registerItemProcessEvents(chunkProcessor);
registerItemWriteEvents(chunkProcessor);
registerSkipEvents(chunkProcessor);
}
}
}
return bean;
}