find Declared Field With Annotation - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

find Declared Field With Annotation

Demo Code

/*/*from  w w  w. j a v  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 {
    public static void main(String[] argv) throws Exception {
        Class annoClazz = String.class;
        Class clazz = String.class;
        System.out
                .println(findDeclaredFieldWithAnnoation(annoClazz, clazz));
    }

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

        return null;
    }
}

Related Tutorials