find Annotation in a Class - Java java.lang.annotation

Java examples for java.lang.annotation:Class Annotation

Description

find Annotation in a Class

Demo Code


import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main{
    public static void main(String[] argv) throws Exception{
        Class clazz = String.class;
        Class annotationType = String.class;
        System.out.println(findAnnotation(clazz,annotationType));
    }//from   w  w  w. j  av a  2s .  c o  m
    public static <A extends Annotation> A findAnnotation(Class<?> clazz,
            Class<A> annotationType) {
        Assert.notNull(clazz, "Class must not be null");
        A annotation = clazz.getAnnotation(annotationType);
        if (annotation != null) {
            return annotation;
        }
        for (Class<?> ifc : clazz.getInterfaces()) {
            annotation = findAnnotation(ifc, annotationType);
            if (annotation != null) {
                return annotation;
            }
        }
        if (!Annotation.class.isAssignableFrom(clazz)) {
            for (Annotation ann : clazz.getAnnotations()) {
                annotation = findAnnotation(ann.annotationType(),
                        annotationType);
                if (annotation != null) {
                    return annotation;
                }
            }
        }
        Class<?> superClass = clazz.getSuperclass();
        if (superClass == null || superClass == Object.class) {
            return null;
        }
        return findAnnotation(superClass, annotationType);
    }
    public static <A extends Annotation> A findAnnotation(Method method,
            Class<A> annotationType) {
        Assert.notNull(method, "Method must not be null");

        A annotation = method.getAnnotation(annotationType);
        if (annotation != null) {
            return annotation;
        }

        return null;
    }
    public static <A extends Annotation> A findAnnotation(Field field,
            Class<A> annotationType) {
        Assert.notNull(field, "Method must not be null");

        A annotation = field.getAnnotation(annotationType);
        if (annotation != null) {
            return annotation;
        }

        return null;
    }
}

Related Tutorials