Here you can find the source of findAnnotation(final Class> type, final Class annotationType)
Parameter | Description |
---|---|
type | The class whose hierarchy to search. |
annotationType | The annotation type to search for. |
A | The annotation type. |
@Nullable public static <A extends Annotation> A findAnnotation(final Class<?> type, final Class<A> annotationType)
//package com.java2s; //License from project: Apache License import java.lang.annotation.Annotation; import java.lang.reflect.*; import javax.annotation.Nullable; public class Main { /**//w w w . j a va 2 s . c o m * Recursively search a type's inheritance hierarchy for an annotation. * * @param type The class whose hierarchy to search. * @param annotationType The annotation type to search for. * @param <A> The annotation type. * * @return The annotation of the given annotation type in the given type's hierarchy or {@code null} if the type's hierarchy * contains no classes that have the given annotation type set. */ @Nullable public static <A extends Annotation> A findAnnotation(final Class<?> type, final Class<A> annotationType) { A annotation = type.getAnnotation(annotationType); if (annotation != null) { return annotation; } for (final Class<?> subType : type.getInterfaces()) { annotation = findAnnotation(subType, annotationType); if (annotation != null) { return annotation; } } if (type.getSuperclass() != null) { annotation = findAnnotation(type.getSuperclass(), annotationType); if (annotation != null) { return annotation; } } return null; } /** * Recursively search a method's inheritance hierarchy for an annotation. * * @param method The method whose hierarchy to search. * @param annotationType The annotation type to search for. * @param <A> The annotation type. * * @return The annotation of the given annotation type in the given method's hierarchy or {@code null} if the method's hierarchy * contains no methods that have the given annotation type set. */ @Nullable public static <A extends Annotation> A findAnnotation(final Method method, final Class<A> annotationType) { A annotation = method.getAnnotation(annotationType); if (annotation != null) { //logger.debug( "Found annotation {} on {}", annotationType, method ); return annotation; } //logger.debug( "Digging down method for annotation {}, {}", annotationType, method ); Method superclassMethod = null; Class<?> superclass = method.getDeclaringClass(); while ((superclass = superclass.getSuperclass()) != null) { try { //logger.debug( "Trying for method {} in {}", method.getName(), superclass ); superclassMethod = superclass.getMethod(method.getName(), method.getParameterTypes()); } catch (final NoSuchMethodException ignored) { } } if (superclassMethod == null) { //logger.debug( "Gave up for annotation {} (reached end of hierarchy)", annotationType ); return null; } return findAnnotation(superclassMethod, annotationType); } }