Java Reflection Annotation Find findAnnotation(Class clazz, Class annotationClass)

Here you can find the source of findAnnotation(Class clazz, Class annotationClass)

Description

Returns the annotation on the given class or the package of the class.

License

Apache License

Parameter

Parameter Description
T class type
clazz The class to search for the annotation.
annotationClass The Class of the annotation.

Return

The annotation or null.

Declaration

public static <T extends Annotation> T findAnnotation(Class<?> clazz,
        Class<T> annotationClass) 

Method Source Code

//package com.java2s;
/*//from   www.ja v a 2  s  . c om
 * Copyright 2002-2006,2009 The Apache Software Foundation.
 * 
 * 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 {
    /**
     * Returns the annotation on the given class or the package of the class. This searchs up the
     * class hierarchy and the package hierarchy for the closest match.
     *
     * @param   <T> class type
     * @param   clazz The class to search for the annotation.
     * @param   annotationClass The Class of the annotation.
     * @return  The annotation or null.
     */
    public static <T extends Annotation> T findAnnotation(Class<?> clazz,
            Class<T> annotationClass) {
        T ann = clazz.getAnnotation(annotationClass);
        while (ann == null && clazz != null) {
            ann = clazz.getAnnotation(annotationClass);
            if (ann == null) {
                ann = clazz.getPackage().getAnnotation(annotationClass);
            }
            if (ann == null) {
                clazz = clazz.getSuperclass();
                if (clazz != null) {
                    ann = clazz.getAnnotation(annotationClass);
                }
            }
        }

        return ann;
    }
}

Related

  1. findAnnotation(Class clazz, Class annotationType)
  2. findAnnotation(Class clazz, Class annotationType)
  3. findAnnotation(Class clazz, Class annotationType)
  4. findAnnotation(Class clazz, Class annotationClass)
  5. findAnnotation(Class clazz, Class annotationClass)
  6. findAnnotation(Class clazz, Class annotationType)
  7. findAnnotation(Class klass, Class annotationClass)
  8. findAnnotation(final Class clazz, final Class type)
  9. findAnnotation(final Class clazz, final Class annotation)