集册 Java实例教程 检索指定类的字段列表如果递归为true,则从所有类层次结构中检索字段

检索指定类的字段列表如果递归为true,则从所有类层次结构中检索字段

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

671
检索指定类的字段列表如果递归为true,则从所有类层次结构中检索字段
/**N o w  J a v a  .   c o m**/


//package com.nowjava;


import java.lang.reflect.Field;

import java.util.Collections;

import java.util.LinkedList;

import java.util.List;


public class Main {



    /**

     * 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);


        Class superClass = clazz.getSuperclass();


        if (superClass != null && recursively) {

            Field[] declaredFieldsOfSuper = getDeclaredFields(superClass,

                    recursively);/*来自 N o w J a v a . c o m - 时代Java*/

            
展开阅读全文