集册 Java实例教程 检索指定类的字段列表,并由传入的注释类进行注释。如果递归为true,则从所有类层次结构中检索字段

检索指定类的字段列表,并由传入的注释类进行注释。如果递归为true,则从所有类层次结构中检索字段

欢马劈雪     最近更新时间:2020-01-02 10:19:05

501
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
检索指定类的字段列表,并由传入的注释类进行注释。如果递归为true,则从所有类层次结构中检索字段
/* from NowJava.com*/


//package com.nowjava;

import java.lang.annotation.Annotation;

import java.lang.reflect.Field;

import java.util.Collections;

import java.util.LinkedList;

import java.util.List;


public class Main {

    public static void main(String[] argv) throws Exception {

        Class clazz = String.class;

        Class annotationClass = String.class;

        boolean recursively = true;

        System.out.println(java.util.Arrays

                .toString(getAnnotatedDeclaredFields(clazz,

                        annotationClass, recursively)));

    }


    /**

     * Retrieving fields list of specified class and which

     * are annotated by incoming annotation class

     * If recursively is true, retrieving fields from all class hierarchy

     *

     * @param clazz - where fields are searching

     * @param annotationClass - specified annotation class

     * @param recursively param

     * @return list of annotated fields

     *///from N o w J a v a . c o m - 时代Java

    public static Field[] getAnnotatedDeclaredFields(Class clazz,

            Class<? extends Annotation> annotationClass, boolean recursively) {

        Field[] allFields = getDeclaredFields(clazz, recursively);

        List<Field> annotatedFields = new LinkedList<Field>();

        for (Field field : allFields) {

            if (field.isAnnotationPresent(annotationClass))

                annotatedFields.add(field);

        }


        return annotatedFields.toArray(new Field[annotatedFields.size()]);

    }


    /**

     * Retrieving fields list of specified class

     * If recursively is true, retrieving fields from all class hierarchy

     *

     * @param clazz where fields are searching

     * @param recursively param

     * @return list of fields

     */

    public static Field[] getDeclaredFields(Class clazz, boolean recursively) {

        List<Field> fields = new LinkedList<Field>();

        Field[] declaredFields = clazz.getDeclaredFields();

        Collections.addAll(fields, declaredFields);

展开阅读全文