find Declared Annotation - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Attribute

Description

find Declared Annotation

Demo Code

/*//from w w  w . j  av  a 2 s  .  c o m
 * @(#)AnnotationUtils.java 2013?12?24? ????23:33:33
 *
 * Copyright (c) 2011-2013 Makersoft.org all rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *
 */
//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class Main {


    @SuppressWarnings("unchecked")
    public static <T extends Annotation> T findDeclaredAnnotation(
            Class<T> annoClazz, Class<?> clazz) {
        for (Field field : clazz.getDeclaredFields()) {
            Annotation[] annos = field.getDeclaredAnnotations();
            for (Annotation anno : annos) {
                if (annoClazz.isAssignableFrom(anno.getClass())) {
                    return (T) anno;
                }
            }
        }

        return null;
    }
}

Related Tutorials