Skip to content

Instantly share code, notes, and snippets.

@junxy
Created September 8, 2022 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junxy/60f8abac6f3d0d9dabcd0665b82bf593 to your computer and use it in GitHub Desktop.
Save junxy/60f8abac6f3d0d9dabcd0665b82bf593 to your computer and use it in GitHub Desktop.
find annotation recursively
package com.demo.util;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@UtilityClass
public class AnnotationExtUtils {
final static int DEFAULT_DEPTH = 10;
@Nullable
public static <A extends Annotation> A findAnnotationRecursively(Method method, Class<A> annotationType) {
return findAnnotationRecursively(method, annotationType, DEFAULT_DEPTH);
}
@Nullable
public static <A extends Annotation> A findAnnotationRecursively(Method method, @NonNull Class<A> annotationType, int depth) {
if (method == null) return null;
depth--;
A annotation = AnnotationUtils.getAnnotation(method, annotationType);
if (annotation == null) {
return findAnnotationRecursively(method.getDeclaringClass(), annotationType, depth);
}
return annotation;
}
@Nullable
public static <A extends Annotation> A findAnnotationRecursively(Class<?> classZ, Class<A> annotationType) {
return findAnnotationRecursively(classZ, annotationType, DEFAULT_DEPTH);
}
@Nullable
public static <A extends Annotation> A findAnnotationRecursively(Class<?> classZ,
@NonNull Class<A> annotationType, int depth) {
if (classZ == null || depth <= 0 || classZ == Object.class) return null;
depth--;
A annotation = AnnotationUtils.getAnnotation(classZ, annotationType);
if (annotation == null) {
return findAnnotationRecursively(classZ.getSuperclass(), annotationType, depth);
}
return annotation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment