Java Reflection Field Set setField(Field field, T newValue, Object instance)

Here you can find the source of setField(Field field, T newValue, Object instance)

Description

set Field

License

Open Source License

Declaration

private static <T> Object setField(Field field, T newValue, Object instance)
            throws IllegalArgumentException, IllegalAccessException 

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    private static <T> Object setField(Field field, T newValue, Object instance)
            throws IllegalArgumentException, IllegalAccessException {
        Object old = null;//from w  w w.j  ava  2 s  . c  om
        final boolean accessible = field.isAccessible();

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

        old = retrieveField(field, instance);
        field.set(instance, newValue);

        field.setAccessible(accessible);

        return old;
    }

    private static Object retrieveField(Field field, Object obj)
            throws IllegalArgumentException, IllegalAccessException {
        Object item = null;
        final boolean accessible = field.isAccessible();

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

        item = field.get(obj);

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

        return item;
    }
}

Related

  1. setField(Field field, Object target, Object value)
  2. setField(Field field, Object target, Object value)
  3. setField(Field field, Object target, Object value)
  4. setField(Field field, Object target, Object value)
  5. setField(Field field, Object target, Object value)
  6. setField(Field field, U instance, Object value)
  7. setField(final Field field, final Object instance, final Object value)
  8. setField(final Field field, final Object object, final Object value)
  9. setField(final O object, final String fieldName, final V value)