Created
September 8, 2022 09:41
-
-
Save junxy/60f8abac6f3d0d9dabcd0665b82bf593 to your computer and use it in GitHub Desktop.
find annotation recursively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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