Get a Hashtable of all class member fields (including private) of the given object - Android java.lang.reflect

Android examples for java.lang.reflect:Field Private

Description

Get a Hashtable of all class member fields (including private) of the given object

Demo Code

/*/*www. j av a 2 s.c  om*/
 * 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.
 */
//package com.java2s;

import java.lang.reflect.Field;

import java.util.HashMap;
import java.util.Map;

public class Main {
    /**
     * 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