find Field By Annotation Class - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

find Field By Annotation Class

Demo Code


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

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        Class annotationClass = String.class;
        System.out.println(findFieldByAnnotationClass(clazz,
                annotationClass));//from   w ww . j a  v a 2s.c  o m
    }

    public static Field findFieldByAnnotationClass(Class<?> clazz,
            Class<? extends Annotation> annotationClass) {
        List<Field> fields = getAllFields(clazz);

        for (Field fld : fields) {
            Annotation[] annotations = fld.getAnnotations();
            for (int i = 0; i < annotations.length; i++) {
                if (annotations[i].annotationType().equals(annotationClass)) {
                    return fld;
                }
            }
        }
        return null;
    }

    public static List<Field> getAllFields(Class<?> type) {
        return getAllFields(null, type);
    }

    private static List<Field> getAllFields(List<Field> fields,
            Class<?> type) {
        if (fields == null)
            fields = new ArrayList<Field>();
        for (Field field : type.getDeclaredFields()) {
            fields.add(field);
        }

        if (type.getSuperclass() != null) {
            fields = getAllFields(fields, type.getSuperclass());
        }

        return fields;
    }
}

Related Tutorials