Returns true if the supplied annotation is present on the target class or any of its super classes. - Java java.lang.annotation

Java examples for java.lang.annotation:Class Annotation

Description

Returns true if the supplied annotation is present on the target class or any of its super classes.

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        Class target = String.class;
        Class annotation = String.class;
        System.out.println(isAnnotationPresent(target, annotation));
    }/*from  w  w  w. j  a v a 2  s  .  com*/

    /**
     * Returns true if the supplied annotation is present on the target class
     * or any of its super classes.
     * 
     * @param annotation Annotation to find.
     * 
     * @return true if the supplied annotation is present on the target class
     * or any of its super classes.
     **/
    public static boolean isAnnotationPresent(Class<?> target,
            Class<? extends Annotation> annotation) {
        Class<?> clazz = target;
        if (clazz.isAnnotationPresent(annotation)) {
            return true;
        }
        while ((clazz = clazz.getSuperclass()) != null) {
            if (clazz.isAnnotationPresent(annotation)) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials