Java Reflection Field Set setField(Object object, Field field, Object value)

Here you can find the source of setField(Object object, Field field, Object value)

Description

Sets the value of a field for a given object, regardless if the field is accessible.

License

Open Source License

Parameter

Parameter Description
object the given object
field the field to set
value the value to give the field

Declaration

public static void setField(Object object, Field field, Object value) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

public class Main {
    /**/*from  w  w  w  .j a v  a 2s.  com*/
     * Sets the value of a field for a given object, regardless if the field is accessible.
     *
     * @param object the given object
     * @param field  the field to set
     * @param value  the value to give the field
     */
    public static void setField(Object object, Field field, Object value) {
        boolean accessible = field.isAccessible();

        if (!accessible) {
            field.setAccessible(true);
        }

        try {
            field.set(object, value);
        } catch (IllegalAccessException shouldNeverHappen) {
            shouldNeverHappen.printStackTrace();
        }

        if (!accessible) {
            field.setAccessible(false);
        }
    }
}

Related

  1. setField(Object obj, String fieldName, Object value, Class valueClass)
  2. setField(Object obj, String name, Object value)
  3. setField(Object obj, String name, Object value)
  4. setField(Object object, Class clazz, String fieldName, Object value)
  5. setField(Object object, Class clazz, String fieldName, Object value)
  6. setField(Object object, Field field, Object value)
  7. setField(Object object, Object value, String name)
  8. setField(Object object, String field, Object value)
  9. setField(Object object, String fieldName, int value)