Here you can find the source of findAnnotation(final Class> clazz, final Class
static <T extends Annotation> T findAnnotation(final Class<?> clazz, final Class<T> annotation)
//package com.java2s; /*/* w ww . j av a 2 s . com*/ * 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; public class Main { static <T extends Annotation> T findAnnotation(final Class<?> clazz, final Class<T> annotation) { checkNotNull(clazz, "clazz is null"); checkNotNull(annotation, "annotation is null"); // Check class and parent classes. Class<?> currentClazz = clazz; while (currentClazz != null) { T a = currentClazz.getAnnotation(annotation); if (a != null) { return a; } Class<?> enclosingClass = currentClazz.getEnclosingClass(); while (enclosingClass != null) { a = findAnnotation(enclosingClass, annotation); if (a != null) { return a; } enclosingClass = enclosingClass.getEnclosingClass(); } final Class<?>[] interfaces = currentClazz.getInterfaces(); for (final Class<?> interfaceClass : interfaces) { a = findAnnotation(interfaceClass, annotation); if (a != null) { return a; } } currentClazz = currentClazz.getSuperclass(); } return null; } static <T> T checkNotNull(final T value, final String msg) { if (value == null) { throw new NullPointerException(msg); } return value; } }