get Fields With Annotation - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

get Fields With Annotation

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 annotation = String.class;
        System.out.println(getFieldsWithAnnotation(clazz, annotation));
    }//from   w  ww  .ja v a2  s.c  o  m

    public static List<Field> getFieldsWithAnnotation(Class<?> clazz,
            Class<? extends Annotation> annotation) {
        Field[] fields = clazz.getDeclaredFields();
        List<Field> annotated = new ArrayList<Field>();
        for (Field field : fields) {
            if (field.isAnnotationPresent(annotation)) {
                annotated.add(field);
            }
        }
        return annotated;
    }
}

Related Tutorials