get Annotation Field - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

get Annotation Field

Demo Code


//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 clazz = String.class;
        Class annotationClass = String.class;
        System.out.println(getAnnotationField(clazz, annotationClass));
    }/*  w w  w.ja v a2 s  .  co  m*/

    public static Field getAnnotationField(Class<?> clazz,
            Class<? extends Annotation> annotationClass) {
        for (Field field : clazz.getDeclaredFields()) {
            if (field.getAnnotation(annotationClass) != null) {
                return field;
            }
        }

        if (clazz.getSuperclass() != null) {
            return getAnnotationField(clazz.getSuperclass(),
                    annotationClass);
        }

        return null;
    }

    public static Field getAnnotationField(Object obj,
            Class<? extends Annotation> annotationClass) {
        return getAnnotationField(obj.getClass(), annotationClass);
    }
}

Related Tutorials