io.github.resilience4j.utils.AnnotationExtractor Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of resilience4j-spring Show documentation
Show all versions of resilience4j-spring Show documentation
Resilience4j is a lightweight, easy-to-use fault tolerance library designed for Java8 and functional programming
package io.github.resilience4j.utils;
import io.github.resilience4j.core.lang.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.util.Objects;
public class AnnotationExtractor {
private static final Logger logger = LoggerFactory.getLogger(AnnotationExtractor.class);
private AnnotationExtractor() {
}
/**
* extract annotation from target class
*
* @param targetClass target class
* @param annotationClass annotation class
* @param The annotation type.
* @return annotation
*/
@Nullable
public static T extract(Class> targetClass, Class annotationClass) {
T annotation = null;
if (targetClass.isAnnotationPresent(annotationClass)) {
annotation = targetClass.getAnnotation(annotationClass);
if (annotation == null && logger.isDebugEnabled()) {
logger.debug("TargetClass has no annotation '{}'", annotationClass.getSimpleName());
annotation = targetClass.getDeclaredAnnotation(annotationClass);
if (annotation == null && logger.isDebugEnabled()) {
logger.debug("TargetClass has no declared annotation '{}'",
annotationClass.getSimpleName());
}
}
}
return annotation;
}
/**
* Extracts the annotation from the target implementation of the Proxy(ies)
*
* @param targetProxy The proxy class
* @param annotationClass The annotation to extract
* @param
* @return
*/
@Nullable
public static T extractAnnotationFromProxy(Object targetProxy,
Class annotationClass) {
if (targetProxy.getClass().getInterfaces().length == 1) {
return extract(targetProxy.getClass().getInterfaces()[0], annotationClass);
} else if (targetProxy.getClass().getInterfaces().length > 1) {
return extractAnnotationFromClosestMatch(targetProxy, annotationClass);
} else {
return null;
}
}
@Nullable
private static T extractAnnotationFromClosestMatch(Object targetProxy,
Class annotationClass) {
int numberOfImplementations = targetProxy.getClass().getInterfaces().length;
for (int depth = 0; depth < numberOfImplementations; depth++) {
T annotation = extract(targetProxy.getClass().getInterfaces()[depth], annotationClass);
if (Objects.nonNull(annotation)) {
return annotation;
}
}
return null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy