Get all field names for the given object - including private fields - Android java.lang.reflect

Android examples for java.lang.reflect:Field Private

Description

Get all field names for the given object - including private fields

Demo Code

/*//from w w  w . j a v  a2 s .c  o  m
 * ClassUtil.java
 * 
 * Avaya Inc. - Proprietary (Restricted) Solely for authorized persons having a
 * need to know pursuant to Company instructions.
 * 
 * Copyright 2013 Avaya Inc. All rights reserved. THIS IS UNPUBLISHED
 * PROPRIETARY SOURCE CODE OF Avaya Inc. The copyright notice above does not
 * evidence any actual or intended publication of such source code.
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;

public class Main{
    /**
     * Get all field names for the given object - including private fields
     * 
     * @param objectInstance Object to get field names for
     * @return String array of all field names
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static String[] getAllFieldNames(Object objectInstance)
            throws IllegalArgumentException, IllegalAccessException // NOSONAR
    {
        Map<String, Object> map = ClassUtil.getAllFields(objectInstance);

        int size = map.size();

        String[] fieldNames = map.keySet().toArray(new String[size]);

        return fieldNames;

    }
    /**
     * Get a Hashtable of all class member fields (including private) of the
     * given object
     * 
     * @param objectInstance Object to get data from
     * @return Hashtable of all values
     * 
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getAllFields(Object objectInstance)
            throws IllegalArgumentException, IllegalAccessException // NOSONAR
    {
        HashMap<String, Object> map = new HashMap<String, Object>();

        Class<? extends Object> clazz = objectInstance.getClass();

        Field fields[] = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);

            String fieldName = f.getName();
            Object fieldValue = f.get(objectInstance);

            map.put(fieldName, fieldValue);
        }

        return map;
    }
}

Related Tutorials