Get the private field data value of the given instance of a class - Android java.lang.reflect

Android examples for java.lang.reflect:Field Private

Description

Get the private field data value of the given instance of a class

Demo Code

/*//from ww  w . ja v a 2 s . co 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.
 */
//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    /**
     * Get the private field data value of the given instance of a class
     * 
     * @param objectInstance Object to get private member data from
     * @param fieldName Name of private member to get data from
     * @return Private member's data
     * 
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static Object getPrivateField(Object objectInstance,
            String fieldName) throws NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException // NOSONAR
    {
        Class<? extends Object> clazz = objectInstance.getClass();

        Field field = clazz.getDeclaredField(fieldName);

        field.setAccessible(true);

        return field.get(objectInstance);
    }
}

Related Tutorials