Look through class hierarchy for Annotation. - Java java.lang.annotation

Java examples for java.lang.annotation:Class Annotation

Description

Look through class hierarchy for Annotation.

Demo Code


//package com.java2s;
import java.lang.annotation.Annotation;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        Class annotationClass = String.class;
        System.out.println(findClassAnnotation(clazz, annotationClass));
    }//ww  w. j ava 2 s.c  o m

    /**
     * Look through class hierarchy.
     */
    public static <A extends Annotation> A findClassAnnotation(
            Class<?> clazz, Class<A> annotationClass) {
        return findClassAnnotation(clazz, annotationClass, true);
    }

    public static <A extends Annotation> A findClassAnnotation(
            Class<?> clazz, Class<A> annotationClass,
            boolean lookThroughClassHierarchy) {
        A annotationResult = null;
        if (annotationClass == null) {
            return annotationResult;
        }

        annotationResult = clazz.getAnnotation(annotationClass);

        // If class has no specified anno, then try to find,
        // whether one of it's superclasses has that anno.
        if ((annotationResult == null) && lookThroughClassHierarchy) {
            Class<?> superClass = clazz.getSuperclass();
            while (superClass != null) {
                annotationResult = superClass
                        .getAnnotation(annotationClass);
                if (annotationResult != null) {
                    return annotationResult;
                }
                superClass = superClass.getSuperclass();
            }
        }

        return annotationResult;
    }
}

Related Tutorials