Set 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

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

Demo Code

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

import java.lang.reflect.Field;

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

        Field field = clazz.getDeclaredField(fieldName);

        field.setAccessible(true);

        field.set(objectInstance, value);
    }
}

Related Tutorials