Here you can find the source of findAnnotationDeclaringClass(Class extends Annotation> annotationType, Class> classToFind)
public static Class<?> findAnnotationDeclaringClass(Class<? extends Annotation> annotationType, Class<?> classToFind)
//package com.java2s; /**/*from w ww . j a v a2s . com*/ * * Copyright (C) norad.fr * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; public class Main { public static Class<?> findAnnotationDeclaringClass(Class<? extends Annotation> annotationType, Class<?> classToFind) { if (hasAnnotation(annotationType, classToFind)) { return classToFind; } Class clazz = classToFind; while (clazz != null && (clazz.getSuperclass() != null || clazz.getInterfaces().length > 0)) { if (hasAnnotation(annotationType, clazz.getSuperclass())) { return clazz.getSuperclass(); } Class<?>[] interfaces = clazz.getInterfaces(); if (interfaces.length > 0) { for (Class declaringInterface : interfaces) { if (hasAnnotation(annotationType, declaringInterface)) { return declaringInterface; } } } clazz = clazz.getSuperclass(); } return null; } private static boolean hasAnnotation(Class annotationType, Class clazz) { return (clazz != null && getAnnotation(clazz, annotationType) != null); // return (clazz != null && clazz.getAnnotation(annotationType) != null); } public static <T extends Annotation> T getAnnotation(AnnotatedElement ae, Class<T> annotationType) { T ann = ae.getAnnotation(annotationType); if (ann == null) { for (Annotation metaAnn : ae.getAnnotations()) { ann = metaAnn.annotationType().getAnnotation(annotationType); if (ann != null) { break; } } } return ann; } }