get Matching Fields By Type Recursively - Android java.lang.reflect

Android examples for java.lang.reflect:Field

Description

get Matching Fields By Type Recursively

Demo Code

/**//from   w w  w.j a  va2  s .  c  om
 * utility functions to extract and set fields in objects using java reflection
 * @author Matthew
 * Copyright (c) 2013 Visible Automation LLC.  All Rights Reserved.
 *
 */
//package com.java2s;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Main {
    public static List<String> getMatchingFieldsByTypeRecursively(Object o,
            Class c) throws IllegalAccessException {
        Stack<Class> breadcrumb = new Stack<Class>();
        breadcrumb.push(o.getClass());
        List<String> result = new ArrayList<String>();
        getMatchingFieldsByTypeRecursively(o, o.getClass(), c, breadcrumb,
                result);
        return result;
    }

    public static void getMatchingFieldsByTypeRecursively(Object o,
            Class objectClass, Class c, Stack<Class> breadcrumb,
            List<String> result) throws IllegalAccessException {
        while ((objectClass != null) && (objectClass != Object.class)) {
            Field fields[] = objectClass.getDeclaredFields();
            for (Field field : fields) {
                if (field.getType() == c) {
                    result.add(getFieldPath(breadcrumb, field));
                } else if (!field.getType().isPrimitive()
                        && (field.getType() != String.class)) {
                    field.setAccessible(true);
                    Object fieldValue = field.get(o);
                    if ((fieldValue != null)
                            && !inBreadcrumb(breadcrumb, field.getType())) {
                        breadcrumb.push(field.getType());
                        getMatchingFieldsByTypeRecursively(fieldValue,
                                field.getType(), c, breadcrumb, result);
                        breadcrumb.pop();
                    }
                }
            }
            objectClass = objectClass.getSuperclass();
        }
    }

    public static String getFieldPath(Stack<Class> breadcrumb, Field field) {
        StringBuffer sb = new StringBuffer();
        for (int i = breadcrumb.size() - 1; i >= 0; i--) {
            Class c = breadcrumb.get(i);
            sb.append(c.getCanonicalName());
            sb.append('.');
        }
        sb.append(field.getName());
        return sb.toString();
    }

    public static boolean inBreadcrumb(Stack<Class> breadcrumb, Class c) {
        for (Class cCand : breadcrumb) {
            if (cCand == c) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials