find Annotation Declaring Class - Java java.lang.annotation

Java examples for java.lang.annotation:Class Annotation

Description

find Annotation Declaring Class

Demo Code

/**/*from www  .  j a  v  a  2s  . c  o  m*/
 *
 *     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.
 */
//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class annotationType = String.class;
        Class classToFind = String.class;
        System.out.println(findAnnotationDeclaringClass(annotationType,
                classToFind));
    }

    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;
    }
}

Related Tutorials